MotionGrafika
MotionGrafika

Reputation: 1131

Adding new Keys to a Dictionary

lst = {}

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

Is there a better way to add to a non-existing key ? In PHP etc it'll create it on its own.

Upvotes: 1

Views: 198

Answers (2)

dvim
dvim

Reputation: 2253

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

Upvotes: 0

khachik
khachik

Reputation: 28693

lst = collections.defaultdict(list)

Upvotes: 3

Related Questions