Ali Ahmad
Ali Ahmad

Reputation: 1055

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 i.e 3 against id:1

Upvotes: 0

Views: 58

Answers (2)

holdenweb
holdenweb

Reputation: 37193

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}

Upvotes: 1

kfb
kfb

Reputation: 6542

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

Upvotes: 3

Related Questions