Dict = [{'type':'a','no':'1'},{'type':'b','no':'2'},{'type':'b','no':'3'},{'type':'a','no':'4'},{'type':'c','no':'5'},{'type':'a','no':'6'}]
I need the count of values in type, Output as follows
a = 3
b = 2
c = 1
CodePudding user response:
from collections import Counter
Dict = [{'type':'a'},{'type':'b'},{'type':'b'},{'type':'a'},{'type':'c'},{'type':'a'}]
lst = [v for a in Dict for k,v in a.items() if k=='type']
Dict = Counter(lst)
for k,v in Dict.items():
print(f'{k} = {v}')
OUTPUT
a = 3
b = 2
c = 1
CodePudding user response:
You can use an intermediate dictionary or even import Counter from the collections module. Here's how you could do it without any additional import:
Dict = [{'type':'a','no':'1'},{'type':'b','no':'2'},{'type':'b','no':'3'},{'type':'a','no':'4'},{'type':'c','no':'5'},{'type':'a','no':'6'}]
result = dict()
for d in Dict:
result[d['type']] = result.get(d['type'], 0) 1
for k, v in result.items():
print(f'{k} = {v}')