Most efficient way to add new keys or append to old keys in a dictionary during iteration in Python?
iteration, python
Solution
Use `collections.defaultdict`, where the default value is a new `list` instance.
>>> import collections
>>> mydict = collections.defaultdict(list)
In this way calling `.append(...)` will always succeed, because in case of a non-existing key `append` will be called on a fresh empty list.
You can instantiate the `defaultdict` with a previously generated list, in case you get the dict `likes` from another source, like so:
>>> mydict = collections.defaultdict(list, likes)
Note that using `list` as the `default_factory` attribute of a `defaultdict` is also discussed as an example in the documentation.
Problem
Here's a common situation when compiling data in dictionaries from different sources: Say you have a dictionary that stores lists of things, such as things I like: ``` likes = { 'colors': ['blue','red','purple'], 'foods': ['apples', 'oranges'] } ``` and a second dictionary with some related values in it: ``` favorites = { 'colors':'yellow', 'desserts':'ice cream' } ``` You then want to iterate over the "favorites" object and either append the items in that object to the list with the appropriate key in the "likes" dictionary or add a new key to it with the value being a list containing the value in "favorites". There are several ways to do this: ``` for key in favorites: if key in likes: likes[key].append(favorites[key]) else: likes[key] = list(favorites[key]) ``` or ``` for key in favorites: try: likes[key].append(favorites[key]) except KeyError: likes[key] = list(favorites[key]) ``` And many more as well... I generally use the first syntax because it feels more pythonic, but if there are other, better ways, I'd love to know what they are. Thanks!