2016-12-02 161 views
2

我想計算字典中每個值的數量,並構造一個新的值作爲關鍵字,以及一個表示值爲值的關鍵字列表。Python:計算字典中的頻率

Input : 
b = {'a':3,'b':3,'c':8,'d':3,'e':8} 
Output: 
c = { '3':[a. b. d] 
     '8':[c, e] 
        } 

我寫了以下內容,但它引發了一個關鍵錯誤,並沒有給出任何輸出,有人可以幫忙嗎?

def dictfreq(b): 
    counter = dict() 
    for k,v in b.iteritems(): 
     if v not in counter: 
      counter[v].append(k) 
     else: 
      counter[v].append(k) 

    return counter 


print dictfreq(b) 
+0

'如果v不在計數器中:' - 如果在計數器字典中沒有'v',爲什麼你要求它只是在下面行? '計數器[V] .append(東西)'? –

+0

我知道你想自己實現這一點,但只是爲了記錄:'itertools'模塊中有一個內置計數器 – RafaelC

回答

3

更改此

if v not in counter: 
     counter[v].append(k) 
    else: 
     counter[v].append(k) 

這樣:實現這個

if v not in counter: 
     counter[v] = [] # add empty `list` if value `v` is not found as key 
    counter[v].append(k) 
+0

這工作,謝謝。這是我可以避免重大錯誤的一般方式嗎?只要申報一個空的字符串/列表/ whathaveyou到位? – onlyf

+0

@onlyf確實如此。像'defaultdict'這樣的其他解決方案完全可以做到。 – freakish

+0

好的,謝謝!對於像我這樣的新人來說,這一直是頭痛的問題。 – onlyf

5

更好的方式是通過collections.defaultdict。例如:

from collections import defaultdict 
b = {'a':3,'b':3,'c':8,'d':3,'e':8} 

new_dict = defaultdict(list) # `list` as default value 
for k, v in b.items(): 
    new_dict[v].append(k) 

通過new_dict終值保持將是:

{8: ['c', 'e'], 3: ['a', 'b', 'd']} 
1

您可以使用dict.setdefault方法:

>>> c = {} 
>>> for key, value in b.iteritems(): 
...  c.setdefault(value, []).append(key) 
... 
>>> c 
{8: ['c', 'e'], 3: ['a', 'b', 'd']} 

在Python3使用b.items()代替。