Find out if there are any entries in the dictionary

I have this list:

source = ['sourceid', 'SubSourcePontiflex', 'acq_source', 'OptInSource', 'source', 'SourceID', 'Sub-Source', 'SubSource', 'LeadSource_295', 'Source', 'SourceCode', 'source_code', 'SourceSubID'] 

I am iterating over XML in python to create a dictionary for each child node. The dictionary varies in length and keys with each iteration. Sometimes a dictionary contains a key, which is also an element in this list. This is sometimes not the case. What I want to do is if the key in the dictionary is also an item in this list, then add this value to the new list. If none of the keys in the dictionary are in the source of the list, I would like to add a default value. I really have a brain block how to do this. Any help would be greatly appreciated.

+4
source share
5 answers

Just use the in keyword to check if a key is in the dictionary.

The following example will print [3, 1] , since 3 and 1 are keys in the dictionary, as well as list items.

 someList = [8, 9, 7, 3, 1] someDict = {1:2, 2:3, 3:4, 4:5, 5:6} intersection = [i for i in someList if i in someDict] print(intersection) 

You can simply check if this intersection list is empty at each iteration. If the list is empty, you know that no items in the list are keys in the dictionary.

+7
source
 in_source_and_dict = set(mydict.keys()).intersection(set(source)) in_dict_not_source = set(mydict.keys()) - set(source) in_source_not_dict = set(source) - set(mydict.keys()) 

Iterate over the results you want. In this case, I think you will want to iterate over in_source_not_dict to provide default values.

+4
source

In Python 3, you can perform specified operations directly with the object returned by dict.keys() :

 in_source_and_dict = mydict.keys() & source in_dict_not_source = mydict.keys() - source in_source_not_dict = source - mydict.keys() 

This will also work in Python 2.7 if you replace .keys() with .viewkeys() .

+2
source
 my_dict = { some values } values = [] for s in sources: if my_dict.get(s): values += [s] if not values: values += [default] 

You can scroll through the sources array and see if there is a value for this source in the dictionary. If there is, add it to the values. After this loop, if the values ​​are empty, add vaule by default.

Please note: if you have a key, a pair of values ​​in the dictionary (val, None), you will not add the value None to the end of the list. If this is a problem, you probably will not want to use this solution.

+1
source

You can do this with any() function

 dict = {...} keys = [...] if not any(key in dict for key in keys): # no keys here 

Equivalently, with all() (DeMorgan laws):

 if all(key not in dict for key in keys): # no keys here 
+1
source

Source: https://habr.com/ru/post/1501718/


All Articles