[英]How to create a frequency dictionary with list of values in python 3.6
I am trying to write a function in python 3.6 that returns a dictionary with item count being the key and a list of items that have that count.我正在尝试在 python 3.6 中编写一个 function ,它返回一个字典,其中项目计数是键和具有该计数的项目列表。
Here is an example of what a test case should look like: Input: {'x':3, 'y':3, 'z':100} Output: {3: ['x', 'y'], 100: ['z']}下面是一个测试用例的示例: 输入:{'x':3, 'y':3, 'z':100} Output: {3: ['x', 'y'], 100 :['z']}
This is what I have for code so far:到目前为止,这就是我的代码:
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
My questions here are how can I set each of the count values as keys, and how can I make a corresponding list of each item that has that count?我的问题是如何将每个计数值设置为键,以及如何为具有该计数的每个项目制作相应的列表?
Thanks for the help!谢谢您的帮助!
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: output:
defaultdict(<class 'list'>, {3: ['x', 'y'], 100: ['z']})
{3: ['x', 'y'], 100: ['z']}
Try this:尝试这个:
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)
for the sake of a different approach..you can do this in pandas pretty easily:为了不同的方法..你可以很容易地在 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: output:
{3: ['x', 'y'], 100: ['z']}
there's probably a way around having a separate line to initialize df['vars'], or maybe not needed at all but couldn't get it to work otherwise可能有一种方法可以使用单独的行来初始化 df['vars'],或者可能根本不需要但无法让它工作
EDIT - maybe a bit less pretty, but shorter:编辑 - 可能不那么漂亮,但更短:
df = pd.DataFrame({'vals':[*in_dict.values()],'vars':[*in_dict.keys()]})
out_dict = df.groupby('vals')['vars'].agg(list).to_dict()
try this:尝试这个:
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.