向字典添加新键

时间:2010-12-07 15:24:02

标签: python list

lst = {}

try:
    lst[someKey].append(someValue)
except KeyError:
    lst[someKey] = []
    lst[someKey].append(someValue) # redundant ?

有没有更好的方法来添加到不存在的密钥?在PHP等中,它将自己创建它。

2 个答案:

答案 0 :(得分:3)

lst = collections.defaultdict(list)

答案 1 :(得分:0)

lst[someKey] = lst.get(someKey, []) + [someValue]