python - 在 Python 字典列表上使用 counter

标签 python dictionary counter

我正在尝试在字典列表上使用计数器来计算每个字典重复自身的次数。

并非列表中的所有字典都必须具有相同的键。

假设我有以下列表:

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/

相关文章:

c++ - 为什么我不能像这样替换字符串上的字符?

c++ - 清除图像映射

java - 等待恰好 n 个工作完成 : Producer, 消费者和计数器

python - 计算列表中连续元素的数量

Python矩阵添加对角线元素

python - 需要帮助理解和修复 pandas 的波动性实现

python - 使用 python 和 selenium 抓取动态网页

Python无法导入ssl模块

c++主要外部函数之间的共享列表

数字序列的 SAS 计数器