python - 如何在 python 3.6 中创建带有值列表的频率字典

标签 python list dictionary python-3.6

我正在尝试在 python 3.6 中编写一个函数,该函数返回一个字典,其中项目计数为键,以及具有该计数的项目列表。

以下是测试用例的示例: 输入:{'x':3,'y':3,'z':100} 输出:{3: ['x', 'y'], 100: ['z']}

这是我到目前为止的代码:

def get_count_items(key_count):
    # create blank dictionary
    count_items = {}
    #for each item_key in key_count:
    for item_key in key_count
    # retrieve its value (which is a count)
    # if the count (as key) exists in count_items:
    if item in count_items:
        count_items[item] += 1
    # append the item_key to the list
    # else:
    #add the count:[item_key] pair to count_items dictionary
    else:
        count_items[item] = 1

    for key, value in count_items.items():
    #return count_items dictionary
        return count_items

我的问题是如何将每个计数值设置为键,以及如何为具有该计数的每个项目创建相应的列表?

感谢您的帮助!

最佳答案

from collections import defaultdict

d = {'x':3, 'y':3, 'z':100} 

# create defaultdict with list type. 
res = defaultdict(list)

# iterate over key value pair
for k, v in d.items():
    res[v].append(k)
print(res)
# or
print(dict(res))

输出:

defaultdict(<class 'list'>, {3: ['x', 'y'], 100: ['z']})
{3: ['x', 'y'], 100: ['z']}

关于python - 如何在 python 3.6 中创建带有值列表的频率字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58966451/

相关文章:

python - 如何使函数定期运行特定持续时间

python - 使用Python修改现有文本文件中的参数

java - Java/Python 的动态链接库可以在 C/C++ 中访问吗?

java - 如何基于列表的最后一个节点(未知类型)创建对象并添加到列表的最后一个?

c++ - 使用 map<int, Foo> 而不是 vector<Foo> 来避免指针失效

python - 如何合并两个csv文件?

Python -TypeError : 'int' object is not iterable

python - 如何获取每个字符串变体以及每个位置的可能性列表

c# - 如何在消息框中写入字典的内容?

python - 将数组的 Python 字典转换为数据框