Python add to Dictionary

Filed Under: Python

Python dictionary is one of the built-in data types. Dictionary elements are key-value pairs.

Python add to Dictionary

There is no explicitly defined method to add a new key to the dictionary. If you want to add a new key to the dictionary, then you can use assignment operator with dictionary key.


dict[key] = value

Note that if the key already exists, then the value will be overwritten.

Let’s look at a simple example to add new keys to a dictionary.


d = {'a': 1, 'b': 2}
print(d)
d['a'] = 100  # existing key, so overwrite
d['c'] = 3  # new key, so add
d['d'] = 4
print(d)

Output:


{'a': 1, 'b': 2}
{'a': 100, 'b': 2, 'c': 3, 'd': 4}

What if we want to add a key only if it’s not present in the dictionary. We can use if condition to achieve this.


if 'c' not in d.keys():
    d['c'] = 300

if 'e' not in d.keys():
    d['e'] = 5

print(d)

Output:


{'a': 100, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Notice that ‘c’ value is not changed because of if condition.

That’s all for adding keys to a dictionary in python.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages