Python:计算字典中的频率

2024-10-03 15:27:03 发布

您现在位置: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)

Tags: in列表forinputoutput字典def错误
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)

您可以使用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()。你知道吗

实现这一点的更好方法是使用^{}。例如:

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']}

相关问题 更多 >