python - 将项目添加到列表的字典
问题描述
假设一个字典,其键是哈希值(或任何东西),其元素是共享该哈希值的项目列表。一种编码方式:
def add_item(dict_of_lists, item):
key = item.get_key()
if key in dict_of_lists:
# at least one item already maps to this key
dict_of_lists[key].append(item)
else:
# this is the first item to map to this key
dict_of_lists[key] = [item]
是否有更 Pythonic(或更优雅,或更高效)的方式来完成此任务?
解决方案
尝试使用 defaultdict,例如
from collections import defaultdict
dict_of_lists = defaultdict(list)
dict_of_lists[key].append(item)
推荐阅读
- scala - Spark Dataframe 的 where 子句可以将变量作为参数吗?
- java - 如何将可绘制对象分配给小部件按钮
- multithreading - C# - WebDriver - MSTest 框架并行执行
- r - 在 R Shiny 中为进度条使用并行 foreach
- java - PDFBox:PDDocument 和 PDPage 是否相互引用?
- powershell - 为什么 PowerShell 在“Get-Credentials”上意外退出?
- node.js - Mongoose find() 回调实际上没有被调用
- c# - 在同一个“使用”中连接到不同的连接字符串
- json - Android Kotlin 解析嵌套 JSON
- asp.net - 无法加载文件或程序集 'msshrtmi, Version=2.7.0.0 - 什么 SDK 安装它?