python - Check if items in a list exist in dictionary -
my question might little complicated understand here's thing. have nested dictionary looks this:
dict_a = {'one': {'bird':2, 'tree':6, 'sky':1, 'total':9}, 'two': {'apple':3, 'sky':1, 'total':4}, 'three': {'tree':6, 'total':6}, 'four': {'nada':1, 'total':1}, 'five': {'orange':2, 'bird':3, 'total':5} }
and list:
list1 = ['bird','tree'] newlist = []
how can check items in list1 whether in nested dictionary of dict_a , append newlist? output should this:
newlist = ['one','three','five']
since bird , tree happened in nested dictionary of one, 3 , five.
what can think of is:
for s,v in dict_a.items(): s1,v1 in v.items(): item in list1: if item == s1: newlist.append(s)
make list1
set , use dictionary views, , list comprehension:
set1 = set(list1) newlist = [key key, value in dict_a.iteritems() if value.viewkeys() & set1]
in python 3, use value.keys()
, dict_a.items
instead.
this tests if there set intersection between dictionary keys , set of keys looking (an efficient operation).
demo:
>>> dict_a = {'one': {'bird':2, 'tree':6, 'sky':1, 'total':9}, ... 'two': {'apple':3, 'sky':1, 'total':4}, ... 'three': {'tree':6, 'total':6}, ... 'four': {'nada':1, 'total':1}, ... 'five': {'orange':2, 'bird':3, 'total':5} ... } >>> set1 = {'bird','tree'} >>> [key key, value in dict_a.iteritems() if value.viewkeys() & set1] ['three', 'five', 'one']
note dictionary ordering arbitrary (depending on keys used , dictionary insertion , deletion history), output list order may differ.
technically speaking, can use list directly (value.viewkeys() & list1
works) making set states intention more clearly.
Comments
Post a Comment