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

Question:

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}

Asked By: Mark Miller

||

Answers:

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

Answered By: Lucas M. Uriarte

logic

for every value in all the dictionaries in the list, test if value is ‘O’ or ‘EM’

result={
    'EM':0,
    'O':0,
}
for dict_ in lolo:
    for value in dict_.values():
        if value == 'EM':
            result['EM'] += 1
        else: 
            result['O'] += 1

or to make more generic:

for dict_ in lolo:
    for value in dict_.values():
        if result.get(value):
            result[value] += 1
        else:
            result[value] = 1

input

lolo = [{'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'}
        ]
result = {
}

output

{'O': 12, 'EM': 10}
Answered By: Hannon qaoud
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.