1

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?

DonnRK
  • 597
  • 1
  • 6
  • 17
  • What language are you using? It can change depending on that – MiltoxBeyond Nov 17 '15 at 17:07
  • What language are you using? For example, python has a method for giving only unique list members (list_name.sort()), but different languages have different built-in methods/functions. – Vadim Nov 17 '15 at 17:09
  • Apologies... using python27 – DonnRK Nov 17 '15 at 18:22
  • Possible duplicate of [Python - List of unique dictionaries](http://stackoverflow.com/questions/11092511/python-list-of-unique-dictionaries) <-- If you can't use the "cheat" in the first answer, try the second. – Two-Bit Alchemist Nov 17 '15 at 18:34
  • The suggested dupe is "easier" because there is an obvious identifier for the dicts. The general problem is more interesting, they might not be serialisable in any way. – wim Nov 17 '15 at 18:39
  • @Two-Bit Alchemist: Thanks for the suggestion. Not sure how I missed this posting, but it is close to what I needed. This first answer misses the 'count' portion, but I could've gotten there with the second. Certainly not idea (converting back and forth), but it would've worked. Appreciate the response. – DonnRK Nov 17 '15 at 19:09
  • @Two-BitAlchemist: Also, the numpy answer provided in that post looks promising. I will try that on another system, but numpy isn't an option given my current config. – DonnRK Nov 17 '15 at 19:11

1 Answers1

1
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
wim
  • 338,267
  • 99
  • 616
  • 750
  • Thanks for the quick response. This worked perfectly. This is my first time using 'assert' - thanks for introducing me to it. Seems perfectly logical to use assert for inline debugging and checking that assumptions prove true. – DonnRK Nov 17 '15 at 19:14