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?
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).
You can use the dict.popitem
method to obtain the item tuple in each sub-dict first and then join the tuple into a colon-delimited string to pass on to Counter
:
Counter(':'.join(d.popitem()) for d in res)
This returns:
Counter({'isBlack:yes': 2, 'isWhite:no': 1, 'isRed:yes': 1, 'isWhite:yes': 1, 'isRed:no': 1})
Alternatively, instead of using a colon-delimited string as a key, it would be more idiomatic to make the key-value tuples as generated by the dict.items()
method the keys:
Counter(i for d in res for i in d.items())
This returns:
Counter({('isBlack', 'yes'): 2, ('isWhite', 'no'): 1, ('isRed', 'yes'): 1, ('isWhite', 'yes'): 1, ('isRed', 'no'): 1})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.