简体   繁体   中英

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

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.

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}

You can get the intersection of your list and the values of dict1 using sets:

for key in dict1.keys():
    count = len(set(dict1[key]) & set(list1))
    print("{0}: {1}".format(key,count))

While brevity can be great, I thought it would be good to also provide an example that is as close to the OPs original code as possible:

# notice conversion to set for O(1) lookup 
# instead of O(n) lookup where n is the size of the list of desired items

dict1={'first':['hi','nice'], 'second':['night','moon']}
set1= set([ 'nice','moon','hi']) 

for key, values in dict1.items():
    counter = 0
    for val in values: 
        if val in set1:
            counter += 1
    print key, counter

The most simplest and basic approach would be:

dict1={'first':['hi','nice'], 'second':['night','moon']}
list1= [ 'nice','moon','hi']
listkeys=list(dict1.keys())
listvalues=list(dict1.values())
for i in range(0,len(listvalues)):
    ctr=0
    for j in range(0,len(listvalues[i])):
        for k in range(0,len(list1)):
            if list1[k]==listvalues[i][j]:
                ctr+=1
    print(listkeys[i],ctr)

Hope it helps.

Using collections.Counter

from collections import Counter

c = Counter(k for k in dict1 for i in list1 if i in dict1[k])
# Counter({'first': 2, 'second': 1})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM