Reputation: 607
I have a list, and that list contains dictionaries. There may be duplicate dictionaries in the list.
I am trying to get a count of unique dictionaries in the list.
I have tried using collections.Counter, but i receive an error stating the items (dictionaries in my list) are not hashable.
Ultimately, I'd like to return a list containing only unique dictionaries, and each dictionary will contain a new key/value pair with -'cnt': .
Can someone help?
Upvotes: 1
Views: 725
Reputation: 362776
new_list = []
counts = []
for dict_ in your_list:
try:
i = new_list.index(dict_)
except ValueError:
counts.append(1)
new_list.append(dict_)
else:
counts[i] += 1
assert len(counts) == len(new_list)
for dict_, count in zip(new_list, counts):
dict_['cnt'] = count
del counts
Upvotes: 1