Python dict how to create key or append an element to key?
Use dict.setdefault()
:
dic.setdefault(key,[]).append(value)
help(dict.setdefault):
setdefault(...)
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:
Using collections.defaultdict
:
import collections
dict_x = collections.defaultdict(list)
...
dict_x[key].append(value)
Pros: Probably best performance. Cons: Not available in Python 2.4.x.
Using dict().setdefault()
:
dict_x = {}
...
dict_x.setdefault(key, []).append(value)
Cons: Inefficient creation of unused list()
s.
Using try ... except
:
dict_x = {}
...
try:
values = dict_x[key]
except KeyError:
values = dict_x[key] = []
values.append(value)
Or:
try:
dict_x[key].append(value)
except KeyError:
dict_x[key] = [value]
You can use a defaultdict for this.
from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')
This is slightly more efficient than setdefault
since you don't end up creating new lists that you don't end up using. Every call to setdefault
is going to create a new list, even if the item already exists in the dictionary.