简体   繁体   English

Python字典针对每个键计数值

[英]Python Dictionary counting the values against each key

I have a list of dictionaries that looks like this: 我有一个字典列表,看起来像这样:

[{'id':1,'name':'Foo','age':20},{'id':2,'name':'Bar'}]

How can I get count of total values against each key ie 3 against id:1 如何获得每个键的总值计数,即,针对id:1的3

You can use len() on dictionaries to get the number of keys: 您可以在字典上使用len()来获取键数:

>>> a = [{'id':1,'name':'Foo','age':20},{'id':2,'name':'Bar'}]
>>> len(a[0])
3
>>> len(a[1])
2

A more detailed problem description would have been helpful. 更详细的问题描述会有所帮助。 For now I assume that you want the length of each dictionary in the list keyed against the value of the id key. 现在,我假设您希望列表中每个字典的长度都与id键的值相对应。 In which case something like 在这种情况下

val_counts = {d['id']: len(d) for d in dlist}

should meet your needs. 应该可以满足您的需求。 It's a dict comprehension whose keys are the id values and whose values are the lengths of each dictionary in the list. 这是一个dict理解,其键是id值,其值是列表中每个字典的长度。 For your particular data the val_counts dictionary I get is 对于您的特定数据,我得到的val_counts字典是

{1: 3, 2: 2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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