Search code examples
pythontabulate

tabulate counts of all values from all keys in list of dicts


I have a list like this:

[{'migs_ba': 'O',
  'migs_eu': 'O',
  'migs_org': 'O',
  'migs_pl': 'O',
  'migs_vi': 'O',
  'mimag': 'EM',
  'mimarks_c': 'O',
  'mimarks_s': 'EM',
  'mims': 'EM',
  'misag': 'EM',
  'miuvig': 'EM'},
 {'migs_ba': 'O',
  'migs_eu': 'O',
  'migs_org': 'O',
  'migs_pl': 'O',
  'migs_vi': 'O',
  'mimag': 'EM',
  'mimarks_c': 'O',
  'mimarks_s': 'EM',
  'mims': 'EM',
  'misag': 'EM',
  'miuvig': 'EM'}...
]

I would like to tabulate all of the strings that appear as values of any key in that list of dicts, like this

{"O": 12, "EM": 10}


Solution

  • this should work considering you name your list "elements"

    from collections import Counter
    
    counter = Counter([val for ele in elements for val in ele.values()])
    print(counter)
    

    output

    Counter({'O': 12, 'EM': 10})
    

    Note the counter inherits from dict, and has all methods and behaviour of it