Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare a list with values in dictionary

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

like image 695
Yousra Gad Avatar asked Oct 19 '18 16:10

Yousra Gad


2 Answers

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.

like image 62
timgeb Avatar answered Sep 23 '22 15:09

timgeb


You can use the following dict comprehension:

{k: sum(1 for i in l if i in list1) for k, l in dict1.items()}

Given your sample input, this returns:

{'first': 2, 'second': 1}
like image 39
blhsing Avatar answered Sep 25 '22 15:09

blhsing