Skip to content
Advertisement

Python3: Get count for same dictionaries within list

I have a list of dictionaries and want to get the unique dictionaries with count. i.e

[{'Basic': 100},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 200}]

Out put should be like

{'Basic': 100} -> 3
{'Basic': 100, 'Food Allowance': 1000} -> 3
{'Basic': 200} -> 1

OR

[index_no] -> count

Advertisement

Answer

Using collections.Counter

  • Dictionary is not hashable so must convert each to a tuple
  • Sort dictionary key, value pairs so initial order does not matter in each dictionary

Code

from collections import Counter

lst = [{'Basic': 100},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 100},
{'Basic': 100, 'Food Allowance': 1000},
{'Basic': 200}]

# Output count of each dictionary
Counter([tuple(sorted(d.items())) for d in lst])

Output

Counter({(('Basic', 100),): 3,
         (('Basic', 100), ('Food Allowance', 1000)): 3,
         (('Basic', 200),): 1})
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement