Python:在字典中计算频率

onl*_*lyf 2 python counter dictionary list python-2.7

我想计算字典中每个值的数量,并构造一个以值为键的新值,以及具有所述值作为值的键列表.

Input :
b = {'a':3,'b':3,'c':8,'d':3,'e':8}
Output:
c = { '3':[a. b. d]
      '8':[c, e]
                    }
Run Code Online (Sandbox Code Playgroud)

我写了以下内容,但它引发了一个关键错误,并没有给出任何输出,有人可以帮忙吗?

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)
Run Code Online (Sandbox Code Playgroud)

Moi*_*dri 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)
Run Code Online (Sandbox Code Playgroud)

持有的最终价值new_dict将是:

{8: ['c', 'e'], 3: ['a', 'b', 'd']}
Run Code Online (Sandbox Code Playgroud)