Jimm Chen
Jimm Chen

Reputation: 3787

More concise way to append a value to a dict array-element?

When I want to append a newvalue into Dict under Key, I find myself have to write:

# Dict={}
# Key = ....
# newvalue = ....

if not Key in Dict:
    Dict[Key] = [ newvalue ]
else:
    Dict[Key].append(newvalue)

It costs four lines of code. Is there a more concise way with python standard library? e.g

Dict.appendkeyvalue(Key, newvalue)

Upvotes: 3

Views: 109

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336428

With standard dictionaries, you can use setdefault():

d = {}
d.setdefault("something", []).append(3)

setdefault() here returns d["something"] if it exists, otherwise it creates a new dictionary entry with [] as its value and returns that.

Upvotes: 3

James
James

Reputation: 25543

You can use a defaultdict:

from collections import defaultdict

d = defaultdict(list)

d['something'].append(3)
print d['something']
# > [3]

Upvotes: 6

Related Questions