2012-02-22 127 views
3

我已经有包含这样的值的字典 {a:3,b:9,c:88,d:3} 我想计算特定数字出现在上面字典中的次数。 例如,在上述词典3字典 出现两次请帮忙写python脚本计算字典中的值的频率

回答

9

你应该使用collections.Counter

>>> from collections import Counter 
>>> d = {'a':3, 'b':9, 'c':88, 'd': 3} 
>>> Counter(d.values()).most_common() 
[(3, 2), (88, 1), (9, 1)] 
+1

(对于大型辞书,'.itervalues()'可能是PY 2.X更有效) – Amber 2012-02-22 18:55:50

+0

好一点。但是因为我个人使用Python 3,并且'values'恰好适用于这两个版本,所以我只是将必要的更改添加到Python 2程序员必须解决的怪癖列表中;) – phihag 2012-02-22 19:02:02

+0

是的。 :)只是注意到未来的读者,而不是建议你改变你的答案。 – Amber 2012-02-22 21:11:17

1

我会使用一个defaultdict做到这一点(基本的更一般的版本柜台)。这已经在2.4以来。

from collections import defaultdict 
counter = defaultdict(int) 

b = {'a':3,'b':9,'c':88,'d':3} 
for k,v in b.iteritems(): 
    counter[v]+=1 

print counter[3] 
print counter[88] 

#will print 
>> 2 
>> 3 
+2

使用'itervalues' ...注意你的代码片段中没有使用'k'吗? – 2012-02-22 19:47:02