小编lir*_*ibo的帖子

在 Python 字典列表上使用 counter

我正在尝试在字典列表上使用 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"})
Run Code Online (Sandbox Code Playgroud)

我想要的解决方案是

solution={
 {"id":1,"first_name":"Jhon","last_name":"Smith"}:2
 {"id":2,"first_name":"Jeff","last_name":"Levi"}:1
 {"id":3,"first_name":"Jhon"}}
Run Code Online (Sandbox Code Playgroud)

我试过了

import collections
c=collections.Counter(my_list)
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误

TypeError: unhashable type: 'dict'
Run Code Online (Sandbox Code Playgroud)

你有什么建议吗

谢谢

python counter dictionary

3
推荐指数
1
解决办法
1557
查看次数

标签 统计

counter ×1

dictionary ×1

python ×1