0

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

0

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.