Skip to main content
 首页 » 编程设计

python 效率: counting key occurrences in dict

2025年05月04日17Leo_wl

尝试获取 dict 键的唯一值以及它们在 list 中出现的次数。这有效,但感觉很糟糕:

a = [ {'pid': 1 }, {'pid': 1}, {'pid': 1}, {'pid': 2}, {'pid': 2}, {'pid': 3} ] 
b = { x['pid']: len([f for f in a if f['pid'] == x['pid']]) for x in a } 
b 

产量:

{1: 3, 2: 2, 3: 1} 

还有更好的方法吗?

请您参考如下方法:

是的,有。使用 collections.Counter :

from collections import Counter 
 
c = Counter(d['pid'] for d in a) 
print(c) 
# Counter({1: 3, 2: 2, 3: 1})