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}
CodePudding user response:
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
CodePudding user response:
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}