首页 > 解决方案 > 将项目添加到列表的字典

问题描述

假设一个字典,其键是哈希值(或任何东西),其元素是共享该哈希值的项目列表。一种编码方式:

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(或更优雅,或更高效)的方式来完成此任务?

标签: pythonpython-3.xdictionary

解决方案


尝试使用 defaultdict,例如

from collections import defaultdict
dict_of_lists = defaultdict(list)
dict_of_lists[key].append(item)

推荐阅读