我正在尝试在字典列表上使用计数器来计算每个字典重复自身的次数。
并非列表中的所有字典都必须具有相同的键。
假设我有以下列表:
my_list=({"id":1,"first_name":"Jhon","last_name":"Smith"},{"id":2,"first_name":"Jeff","last_name":"Levi"},{"id":3,"first_name":"Jhon"},{"id":1,"first_name":"Jhon","last_name":"Smith"})
我想要的解决方案是
solution={
{"id":1,"first_name":"Jhon","last_name":"Smith"}:2
{"id":2,"first_name":"Jeff","last_name":"Levi"}:1
{"id":3,"first_name":"Jhon"}}
我已经尝试过
import collections
c=collections.Counter(my_list)
但我收到以下错误
TypeError: unhashable type: 'dict'
你有什么建议吗
谢谢
最佳答案
You can't use dictionary
as a key in other dictionary 。这就是为什么您会收到 TypeError: unhashable type: 'dict'
。
您可以将字典序列化为 JSON
字符串,该字符串可用作字典键。
import json
import collections
my_list = [{"id":1,"first_name":"Jhon","last_name":"Smith"},
{"id":2,"first_name":"Jeff","last_name":"Levi"},
{"id":3,"first_name":"Jhon"},
{"id":1,"first_name":"Jhon","last_name":"Smith"}]
c = collections.Counter(json.dumps(l) for l in my_list)
print c
>>> Counter({'{"first_name": "Jhon", "last_name": "Smith", "id": 1}': 2,
'{"first_name": "Jeff", "last_name": "Levi", "id": 2}': 1,
'{"first_name": "Jhon", "id": 3}': 1})
关于python - 在 Python 字典列表上使用 counter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37375406/