How can I add new keys to a dictionary?
Hello Sakshi,
You can create a new key/value pair in a dictionary by assigning a value to a key:
d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
If the key doesn’t exist, it will be added with the given value. If the key already exists, its current value will be overwritten with the new value.
Hey Sakshi,
Yes, it is possible to create or update key/value pairs in a dictionary, and although there is a method that implements this, it is not recommended to use it directly.
To demonstrate the proper and improper ways to do this, let’s start by creating an empty dictionary using the dictionary literal {}
:
my_dict = {}
Best Practice 1: Subscript Notation
To add or update a single key and value, you can use subscript notation for item assignment:
my_dict['new key'] = 'new value'
Now, my_dict
is:
{'new key': 'new value'}
Best Practice 2: The update
Method - Two Ways
Method 1: Using a Dictionary
You can efficiently update the dictionary with multiple key-value pairs using the update
method. Note that an extra dictionary might be created in the process:
my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})
Now, my_dict
is:
{'new key': 'new value', 'key 2': 'value 2', 'key 3': 'value 3'}
Method 2: Using Keyword Arguments
Another efficient way to update a dictionary is with keyword arguments in the update
method. This method is more readable but is limited to keys that are valid Python identifiers (no spaces, special symbols, or starting with a number):
my_dict.update(foo='bar', foo2='baz')
Now, my_dict
is:
{'new key': 'new value', 'key 2': 'value 2', 'key 3': 'value 3', 'foo': 'bar', 'foo2': 'baz'}
These are three Pythonic ways to update a dictionary.
Magic Method __setitem__
and Why It Should Be Avoided
There is another way to update a dictionary using the __setitem__
method, but it should be avoided due to poor performance and less readability. Here’s an example:
d = {}
d.__setitem__('foo', 'bar')
print(d) # {'foo': 'bar'}
Let’s compare the performance of subscript notation and __setitem__
:
def f():
d = {}
for i in range(100):
d['foo'] = i
def g():
d = {}
for i in range(100):
d.__setitem__('foo', i)
import timeit
number = 100
print(min(timeit.repeat(f, number=number))) # Faster
print(min(timeit.repeat(g, number=number))) # Slower
As shown, using subscript notation is much faster than using __setitem__
. Using the language in the way it was intended (the Pythonic way) is usually both more readable and computationally efficient.
Hello Sakshi,
Here are some straightforward methods for merging dictionaries in Python 3:
c = dict(a, **b) # See also https://stackoverflow.com/q/2255878
c = dict(list(a.items()) + list(b.items()))
c = dict(i for d in [a, b] for i in d.items())
Note: The first method above only works if the keys in b
are strings.
To add or modify a single element, the b
dictionary would contain only that one element:
c = dict(a, **{'d': 'dog'}) # Returns a dictionary based on 'a'
This is equivalent to:
def functional_dict_add(dictionary, key, value):
temp = dictionary.copy()
temp[key] = value
return temp
c = functional_dict_add(a, 'd', 'dog')