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!
Use
collections.defaultdict, where the default value is a newlistinstance.In this way calling
.append(...)will always succeed, because in case of a non-existing keyappendwill be called on a fresh empty list.You can instantiate the
defaultdictwith a previously generated list, in case you get the dictlikesfrom another source, like so:Note that using
listas thedefault_factoryattribute of adefaultdictis also discussed as an example in the documentation.