I have a dictionary where key is string and value is list.
Now while adding a value associated with given key, I always have to check if there is any list yet, otherwise
There are at least three ways:
Use dict.setdefault
>>> data = {}
>>> data.setdefault('foo', []).append(42)
>>> data
{'foo': [42]}
Use defaultdict
, which unlike .setdefault
, takes a callable:
>>> from collections import defaultdict
>>> data = defaultdict(list)
>>> data
defaultdict(, {})
>>> data['foo'].append(42)
>>> data
defaultdict(, {'foo': [42]})
Finally, subclass dict
and implement __missing__
:
>>> class MyDict(dict):
... def __missing__(self, key):
... self[key] = value = []
... return value
...
>>> data = MyDict()
>>> data['foo'].append(42)
>>> data
{'foo': [42]}
Note, you can think of the last one as the most flexible, you have access to the actual key that's missing when you deal with it. defaultdict
is a class factory, and it generates a subclass of dict
as well. But, the callable is not passed any arguments, nevertheless, it is sufficient for most needs.