将列表与字典中的值进行比较

7

我有一个字典包含值列表和一个列表:

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

我想要将字典中的值和list1进行比较,如果每个键的值出现在列表中,则为这些键制作计数器:输出应如下所示:

   first 2
   second 1

这是我的代码:

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)

有什么帮助吗?提前感谢。

6个回答

7
我会将list1转换成一个set,以便实现O(1)的查找时间和访问intersection方法。然后使用字典推导式。
>>> 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 可以接受任何可迭代的参数,因此无需从 dict1 的值创建集合。


1
我认为这很棒!也许可以添加一个选项,以按照原帖的要求打印输出。 - LeKhan9

2
您可以使用以下字典解析式:
{k: sum(1 for i in l if i in list1) for k, l in dict1.items()}

根据您提供的样例输入,这个返回结果为:
{'first': 2, 'second': 1}

2

您可以使用集合获取列表和dict1的值的交集:

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

1
请注意,在for循环的每次迭代中,从list1创建集合有点冗余。我会将其移到循环之前。 - timgeb
另外,若要遍历字典的键和值,请使用dict.items进行迭代,这样更清晰、更符合习惯用法。同时,在3.6及以上版本中应该考虑使用f-strings而不是str.format - jpp

1
虽然简洁明了很好,但我认为提供一个尽可能接近原始代码的示例也是有益的。
# 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

0

最简单和基本的方法是:

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)

希望能有所帮助。


0

使用 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})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接