Tom J Muthirenthi
Tom J Muthirenthi

Reputation: 3340

List of dict - count occurences

I am trying to achieve,

Before:

dict = [{'name':'count', 'label':'Count'},{'name':'type', 'label':'Type'}, {'name':'count', 'label':'Count1'}]

After:

dict = [{'name':'count', 'label':'Count', 'count': 2},{'name':'type', 'label':'Type', 'count': 1}]

When tried to use :

from collections import Counter
Counter(dict)

It throws TypeError: unhashable type: 'dict'

Upvotes: 0

Views: 84

Answers (3)

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

The solution with Counter, not very pythonic though:

from collections import Counter
d = [{'name': 'count', 'label': 'Count'}, {'name': 'type', 'label': 'Type'}, {'name': 'count', 'label': 'Count'}]

r = [dt.update({'count': count}) or dt for sub, count in Counter(map(lambda i: tuple(i.items()), d)).items() for dt in [dict(sub)]]

The r is:

[{'name': 'count', 'label': 'Count', 'count': 2}, {'name': 'type', 'label': 'Type', 'count': 1}]

Upvotes: 1

Liju
Liju

Reputation: 2303

Below code will help

dict=list({v['name']:v for v in [i for i in dict if i.update({'count':[a['name'] for a in dict].count(i['name'])})==None]}.values())

Upvotes: 1

KevinLi-pythoneer
KevinLi-pythoneer

Reputation: 11

Well, dict cannot be keys to Counter. Because it's mutable. You need to convert your dict into an inmutable type. exmaple:

from collections import Counter
Counter(frozenset(d.items()) for d in dict)

Note: Your code seems to be wrong. There is a '1' after 'Count' in the last dict.

Upvotes: 1

Related Questions