How to add new keys to a dictionary in Python?

In this post, we’ll learn how to add new keys to a dictionary in Python.

How to add new keys to a dictionary in Python?

You create a new key/value pair on a dictionary by assigning a value to that key

d = {'key': 'value'}
print(d)  # {'key': 'value'}

d['mynewkey'] = 'mynewvalue'

print(d)  # {'key': 'value', 'mynewkey': 'mynewvalue'}

If the key doesn’t exist, it’s added and points to that value. If it exists, the current value it points to is overwritten.

For detailed info about dictionaries and other data types in Python, visit this post on data types in Python.

How to add multiple keys to a dictionary simultaneously in Python?

To add multiple keys simultaneously, use dict.update():

>>> x = {1:2}
>>> print(x)
{1: 2}

>>> d = {3:4, 5:6, 7:8}
>>> x.update(d)
>>> print(x)
{1: 2, 3: 4, 5: 6, 7: 8}

For more detailed info, please follow the post below.

Info on dictionaries in Python:

I feel like consolidating info about Python dictionaries:

Creating an empty dictionary

data = {}
# OR
data = dict()

Creating a dictionary with initial values

data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}

Inserting/Updating a single value in a dictionary

data['a'] = 1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
# OR

Inserting/Updating multiple values in a dictionary

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

Python 3.9+:

The update operator |= now works for dictionaries:

data |= {'c':3,'d':4}

Creating a merged dictionary without modifying originals

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2

Python 3.5+:

This uses a new feature called dictionary unpacking.

data = {**data1, **data2, **data3}

Python 3.9+:

The merge operator | now works for dictionaries:

data = data1 | {'c':3,'d':4}

How to delete items in dictionary

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary

How to check if a key is already in dictionary

key in data

How to iterate through pairs in a dictionary

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys

How to create a dictionary from two lists

data = dict(zip(list_with_keys, list_with_values))

If you want to add a dictionary within a dictionary you can do it this way.

Example: Add a new entry to your dictionary & sub dictionary

dictionary = {}
dictionary["new key"] = "some new entry" # add new dictionary entry
dictionary["dictionary_within_a_dictionary"] = {} # this is required by python
dictionary["dictionary_within_a_dictionary"]["sub_dict"] = {"other" : "dictionary"}
print (dictionary)


{'new key': 'some new entry', 'dictionary_within_a_dictionary': {'sub_dict': {'other': 'dictionarly'}}}

NOTE: Python requires that you first add a sub

dictionary["dictionary_within_a_dictionary"] = {}

before adding entries.

Hope you learned something from this post.

Follow Programming Articles for more!

About ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ

Linux and Python enthusiast, in love with open source since 2014, Writer at, India.

View all posts by ᴾᴿᴼᵍʳᵃᵐᵐᵉʳ →