The Python dict() constructor
Summary
How to add key/value pairs to an existing dictionary using the dict() contstructor
Using dict()
I’ve fallen into the habit of building dictionaries in Python using the braces approach, that is :
d1 = {'name':'Jane', 'age':21}
I was reminded today that you can use the conventional constructor method associated with the dict type as follows :
d1 = dict(name='Jane', age=21)
This will produce the same dictionary as the previous example. Notice that name of the keyword arguments (‘name’ and ‘age’) end up being the keys of the dictionary. Notice also that because they are keyword arguments to the function dict() they are not supplied as quoted strings.
What I learnt today
I was looking at some code today and discovered there’s something else the dict() function can do which I didn’t previously know of. If you have an existing dictionary which you wish to add some key/value pairs to you can do this.
#Create d1 from above
d1 = dict(name='Jane', age=21)
#Now produce a new dictionary, d2, based
#upon d1 and with extra key/value pairs
d2=dict(d1, weight=50, shoesize=7)
print d2
{'age': 21, 'shoesize': 7, 'name': 'Jane', 'weight': 50}
Taking it further
Not surprisingly you can use the same technique to modify the existing key/value pairs in a dictionary, like this :
#Create d1 from above
d1 = dict(name='Jane', age=21)
#Now produce a new dictionary, d3, based
#upon d1 with a modified existing key/value pair
d3=dict(d1, name='John')
print d3
{'age': 21, 'name': 'John'}