[英]Dictionary: How to count frequency of values in list - Python3
I've got a dictionary with multiple values for each key. 我有一个字典,每个键都有多个值。 Therefore I'm using a list for the values. 因此,我正在使用值列表。 Now I want to count how often a value occurs in this list of values. 现在,我要计算一个值在此值列表中出现的频率。 For example I've got the following dictionary: 例如,我有以下字典:
dic = {}
dic.setdefault(„Sam“, []).append(„Smith“)
dic.setdefault(„Sam“, []).append(„Miller“)
dic.setdefault(„Sam“, []).append(„Smith“)
So 所以
for k, v in dic.items():
print(k,v)
results in: 结果是:
Sam [Smith, Miller, Smith]
Now I want to count how often each value occurs and print the frequency next to the value itself. 现在,我要计算每个值出现的频率,并在值本身旁边打印频率。 I want the output to look like the following: 我希望输出如下所示:
Smith: 2, Miller: 1
For that purpose I've tried the following code without success: 为此,我尝试了以下代码,但未成功:
D = defaultdict(list)
for i, item in enumerate(mylist):
D[item].append(i)
D = {k: len(v) for k, v in D.items()}
print(D)
This code just works fine for a simple list like: 此代码仅适用于以下简单列表:
mylist = [10, 20, 30, 10, 30]
For such a kind of list the code above will result in what I expect: 对于这样的列表,上面的代码将导致我期望的结果:
{10: 2, 30:2, 20:1}
However it won't work with the list containing the values. 但是,它不适用于包含值的列表。 Instead it shows the following error message when using „dic“ instead of „mylist“ in the 2nd line: 而是在第二行中使用“ dic”而不是“ mylist”时显示以下错误消息:
TypeError: unhashable type: 'list' TypeError:无法散列的类型:“列表”
Would be great if someone could help. 如果有人可以帮助,那就太好了。
That's actually a pretty interesting way of creating a "Count" feature. 这实际上是创建“计数”功能的一种非常有趣的方式。 The issue is that your code counts items in lists, so passing a dictionary to it won't work. 问题是您的代码对列表中的项目进行计数,因此将字典传递给它将不起作用。 Instead, you should pass the values from your dic.items()
. 相反,您应该传递dic.items()
的值。 If we use what you have: 如果我们使用您所拥有的:
for k, v in dic.items():
D = defaultdict(list)
for i, item in enumerate(v):
D[item].append(i)
D = {k: v for k, v in D.items()}
print(k, D)
Also, take a look at collections.Counter
which is a standard library implementation of Count. 另外,看看collections.Counter
,它是Count的标准库实现。
from collections import Counter
for k, v in dic.items():
print(k, Counter(v))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.