简体   繁体   中英

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

You can use len() on dictionaries to get the number of keys:

>>> 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. 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. For your particular data the val_counts dictionary I get is

{1: 3, 2: 2}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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