分组键值对并使用 python 中的 Counter 获取计数 3

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

我有这样一个字典列表:

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

我需要按键值对对 res 进行分组,并使用 Counter 获取它们的计数,如下所示:

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

我试过这个: count = Counter(res) ,但出现如下错误:

TypeError: unhashable type: 'dict'

还有什么我可以尝试的吗?

您只需在生成器表达式中进行一些预处理即可将字典转换为字符串。

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

next(iter(d))是获取字典的第一个key(这里恰好是唯一一个)

可以使用dict.popitem方法先获取每个sub-dict中的item元组,然后将元组join成冒号分隔的字符串传给Counter:

Counter(':'.join(d.popitem()) for d in res)

这个returns:

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

或者,不是使用冒号分隔的字符串作为键,而是将 dict.items() 方法生成的键值元组作为键:

Counter(i for d in res for i in d.items())

这个returns:

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