Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if no items in a list are keys in a 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 the dictionary will contain a key that is also an item in this list. Sometimes it wont. What I want to be able to do is, if a key in the dictionary is also an item in this list then append the value to a new list. If none of the keys in the dictionary are in list source, I'd like to append a default value. I'm really having a brain block on how to do this. Any help would be appreciated.

like image 947
Chris Clouten Avatar asked Dec 06 '22 05:12

Chris Clouten


1 Answers

Just use the in keyword to check for membership of some key in a dictionary.

The following example will print [3, 1] since 3 and 1 are keys in the dictionary and also elements of the list.

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 just check if this intersection list is empty at every iteration. If the list is empty then you know that no items in the list are keys in the dictionary.

like image 132
Shashank Avatar answered Dec 08 '22 20:12

Shashank