[英]Python count items in dict value that is a list
Python 3.3, a dictionary with key-value pairs in this form. Python 3.3,具有这种形式的键值对的字典。
d = {'T1': ['eggs', 'bacon', 'sausage']}
The values are lists of variable length, and I need to iterate over the list items.这些值是可变长度的列表,我需要遍历列表项。 This works:
这有效:
count = 0
for l in d.values():
for i in l: count += 1
But it's ugly.但它很丑。 There must be a more Pythonic way, but I can't seem to find it.
一定有更Pythonic的方式,但我似乎找不到。
len(d.values())
produces 1. It's 1 list (DUH).产生 1. 它是 1 个列表 (DUH)。 Attempts with Counter from here give 'unhashable type' errors.
从这里尝试使用 Counter 会出现“不可哈希类型”错误。
Use sum()
and the lengths of each of the dictionary values:使用
sum()
和每个字典值的长度:
count = sum(len(v) for v in d.itervalues())
If you are using Python 3, then just use d.values()
.如果您使用的是 Python 3,则只需使用
d.values()
。
Quick demo with your input sample and one of mine:使用您的输入示例和我的示例之一进行快速演示:
>>> d = {'T1': ['eggs', 'bacon', 'sausage']}
>>> sum(len(v) for v in d.itervalues())
3
>>> d = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['spam', 'ham', 'monty', 'python']}
>>> sum(len(v) for v in d.itervalues())
7
A Counter
won't help you much here, you are not creating a count per entry, you are calculating the total length of all your values. Counter
在这里对您没有多大帮助,您不是在为每个条目创建计数,而是在计算所有值的总长度。
>>> d = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['spam', 'ham', 'monty', 'python']}
>>> sum(map(len, d.values()))
7
Doing my homework on Treehouse I came up with this.在 Treehouse 做作业时,我想到了这个。 It can be made simpler by one step at least (that I know of), but it might be easier for beginners (like myself) to onderstand this version.
至少可以简化一步(我知道),但对于初学者(如我自己)来说,理解这个版本可能更容易。
dict = {'T1': ['eggs', 'bacon', 'sausage'], 'T2': ['bread', 'butter', 'tosti']}
total = 0
for value in dict:
value_list = dict[value]
count = len(value_list)
total += count
print(total)
For me the simplest way is:对我来说,最简单的方法是:
winners = {1931: ['Norman Taurog'], 1932: ['Frank Borzage'], 1933: ['Frank Lloyd'], 1934: ['Frank Capra']}
win_count_dict = {}
for k,v in winners.items():
for winner in v:
if winner not in win_count_dict:
win_count_dict[winner]=1
else:
win_count_dict[winner]+=1
print("win_count_dict = {}".format(win_count_dict))
I was looking for an answer to this when I found this topic untill I realized I already had something in my code to use this for.当我发现这个主题时,我一直在寻找这个问题的答案,直到我意识到我的代码中已经有一些东西可以使用它。 This is what I came up with:
这就是我想出的:
count = 0
for key, values in dictionary.items():
count = len(values)
If you want to save the count for every dictionary item you could create a new dictionary to save the count for each key.如果您想保存每个字典项的计数,您可以创建一个新字典来保存每个键的计数。
count = {}
for key, values in dictionary.items():
count[key] = len(values)
I couldn't exactly find from which version this method is available but I think .items method is only available in Python 3.我无法确切地找到此方法可用的版本,但我认为 .items 方法仅在 Python 3 中可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.