compare a list with values in dictionary

  • A+

I have a dictionary contains lists of values and a list:

dict1={'first':['hi','nice'], 'second':['night','moon']} list1= [ 'nice','moon','hi'] 

I want to compare the value in the dictionary with the list1 and make a counter for the keys if the value of each key appeared in the list: the output should like this:

   first 2    second 1 

here is my code:

count = 0  for list_item in list1:      for dict_v in dict1.values():       if list_item.split() == dict_v:         count+= 1         print(dict.keys,count) 

any help? Thanks in advance


I would make a set out of list1 for the O(1) lookup time and access to the intersection method. Then employ a dict comprehension.

>>> dict1={'first':['hi','nice'], 'second':['night','moon']} >>> list1= [ 'nice','moon','hi'] >>>  >>> set1 = set(list1) >>> {k:len(set1.intersection(v)) for k, v in dict1.items()} {'first': 2, 'second': 1} 

intersection accepts any iterable argument, so creating sets from the values of dict1 is not necessary.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: