python - 如何在 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']}
推荐阅读
- typescript - 错误:“ObjectBuilder”类型上不存在属性“onChange”
- html - Google Apps 脚本;侧边栏关闭
- vuejs2 - Vuex状态在绑定时将[object Object]插入输入
- python - rtsp 方法设置失败:461 客户端错误
- html - 因此
和其他元素有自己的填充
- php - 获取最多 n 级的 XML 标记和属性
- kotlin - 我如何在 kotlin 中与超类建立一对一的关系
- javascript - 如何替换包含不固定字符的字符串中的某些字符
- c# - XNA/Monogame 中的 Ray 视线
- json - 在 Swift 4 中访问嵌套 JSON 字符串的成员