将项目添加到列表字典的Python方式

时间:2020-05-06 18:39:04

标签: python python-3.x dictionary

我经常使用此代码段:

d = {}
for x in some_list:
    y = some_func(x)  # can be identity 
    if y in d:
        d[y].append(another_func(x))
    else:
        d[y] = [another_func(x)]

这是最Python化的方法吗?还是有更好的方法?我使用Python 3。

1 个答案:

答案 0 :(得分:0)

您可以尝试

from collections import defaultdict

d = defaultdict(list)
for x in some_list:
    d[some_func(x)].append(another_func(x))

defaultdict是一个字典选项,如果要查找的键不存在于字典键中,则可以使用您要分配的类型来初始化它。 在这种情况下,如果键不存在,则每次调用d时,都会创建一个空列表。