![](/img/trans.png)
[英]Python: Compare the key against the values of each key pair values in a dictionary based on the type set in a separate dictionary
[英]Python Dictionary counting the values against each key
我有一个字典列表,看起来像这样:
[{'id':1,'name':'Foo','age':20},{'id':2,'name':'Bar'}]
如何获得每个键的总值计数,即,针对id:1的3
您可以在字典上使用len()
来获取键数:
>>> a = [{'id':1,'name':'Foo','age':20},{'id':2,'name':'Bar'}]
>>> len(a[0])
3
>>> len(a[1])
2
更详细的问题描述会有所帮助。 现在,我假设您希望列表中每个字典的长度都与id
键的值相对应。 在这种情况下
val_counts = {d['id']: len(d) for d in dlist}
应该可以满足您的需求。 这是一个dict理解,其键是id
值,其值是列表中每个字典的长度。 对于您的特定数据,我得到的val_counts
字典是
{1: 3, 2: 2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.