Search code examples
pythonpython-3.xlistdictionarycounter

Group key-value pairs and get count using Counter in python 3


I have a list of dictionaries like this:

res = [{"isBlack": "yes"} , {"isWhite": "no"} , {"isRed": "yes"} , {"isWhite": "yes"} , {"isRed": "no"} , {"isBlack": "yes"}]

I need to group res by key-value pair and get their count using Counter , to look like this:

Counter({"isBlack:yes": 2 , "isWhite:no": 1, "isWhite:yes": 1 , "isRed:no": 1 , "isRed:yes": 1}) 

I tried this: count = Counter(res) , but getting error like:

TypeError: unhashable type: 'dict'

Is there something else I could try?


Solution

  • You just need to do some preprocessing in a generator expression to convert the dicts to strings.

    print(Counter(f"{next(iter(d))}:{d[next(iter(d))]}" for d in res))
    

    next(iter(d)) is to get the first key in a dictionary (which happens to be the only one here).