Python : 计算字典中的频率

Python : Count frequences in dictionary

我想计算字典中每个值的个数,并构造一个以该值为键的新值,以及以该值为值的键列表。

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)

改变这个

    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)

实现此目的的更好方法是使用 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']}

您可以使用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()