[英]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.