Home > Net >  Finding the number of different dict elements in a list of dict in python
Finding the number of different dict elements in a list of dict in python

Time:01-20

I have been given a list of dicts, suppose

L = [
  {'color':'R', 'rank':2},
  {'color':'G', 'rank':1},
  {'color':'G', 'rank':2}, 
  {'color':'R', 'rank':2}, 
  {'color':'Y', 'rank':4}, 
  {'color':'G', 'rank':2}
]

I need to find the find the count of different dict items in the list, i.e. {'color':'R', 'rank':2} has count 2, {'color':'G', 'rank':2} has count 2 etc. Thanks in advance.

CodePudding user response:

Many ways to do this. I like using pandas here, because a list of dicts can easily be represented as a dataframe:

import pandas as pd
pd.DataFrame(L).groupby(["color", "rank"]).size()

Another way is:

from collections import Counter
Counter([f"{d['color']}_{d['rank']}" for d in L])
>>> Counter({'R_2': 2, 'G_1': 1, 'G_2': 2, 'Y_4': 1})

Dicts are not hashable, so we need to convert the dict to something hashable like a string, hence the f-string.

CodePudding user response:

I will try:

x = dict()
for element in L:
  if element['color'] in x:
    x[element['color']] =1
  else:
    x[element['color']]=1

In x you should have the count.

  •  Tags:  
  • Related