Python add to Dictionary

Filed Under: Python
Python Add To Dictionary

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}
d['a'] = 100  # existing key, so overwrite
d['c'] = 3  # new key, so add
d['d'] = 4


{'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



{'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.


  1. KMJ248 says:

    Thank you, this information was clearly laid out!

  2. RTFM says:

    You don`t need keys()
    d={c: alpha}
    if c in d:

  3. Niik says:

    What will happen if you don’t add the .keys()? will it also check if the values of keys are the value you want to input?

  4. confused says:

    thanks it really helped!
    have a question tho, can you make mathematical operations in the values to the keys?

Leave a Reply

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

Generic selectors
Exact matches only
Search in title
Search in content