繁体   English   中英

如何使用 python 3.6 中的值列表创建频率字典

[英]How to create a frequency dictionary with list of values in python 3.6

我正在尝试在 python 3.6 中编写一个 function ,它返回一个字典,其中项目计数是键和具有该计数的项目列表。

下面是一个测试用例的示例: 输入:{'x':3, 'y':3, 'z':100} Output: {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))

output:

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

尝试这个:

a = {'x':3, 'y':3, 'z':100}
d = {}
for x in a:
    if a[x] in d:
        d[a[x]].append(x)
    else:
        d[a[x]]=[x]
print(d)

为了不同的方法..你可以很容易地在 pandas 中做到这一点:

import pandas as pd
df = pd.DataFrame([in_dict]).T
df['vars'] = df.index
out_dict = df.groupby(0)['vars'].agg(list).to_dict()

output:

{3: ['x', 'y'], 100: ['z']}

可能有一种方法可以使用单独的行来初始化 df['vars'],或者可能根本不需要但无法让它工作

编辑 - 可能不那么漂亮,但更短:

df = pd.DataFrame({'vals':[*in_dict.values()],'vars':[*in_dict.keys()]})
out_dict = df.groupby('vals')['vars'].agg(list).to_dict()

尝试这个:

d = {'x':3, 'y':3, 'z':100} 
x={}
for key, value in sorted(d.items()): 
    x.setdefault(value, []).append(key) 

x
{3: ['x', 'y'], 100: ['z']}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM