Reputation: 3787
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
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
Reputation: 25543
You can use a defaultdict
:
from collections import defaultdict
d = defaultdict(list)
d['something'].append(3)
print d['something']
# > [3]
Upvotes: 6