Add key-value pairs to an empty dictionary in Python

This article will discuss different ways to add key-value pairs to an empty dictionary in python, like using [] operator, update() function or dictionary comprehension.

Add key-value pairs to an empty dictionary using [] operator

Suppose we have an empty dictionary like this,

# Creating an empty dictionary
sample_dict = {}


To add a new key-value pair, we can pass the key in the subscript operator and assign a value to it. Like this,

new_key = 'John'
new_value = 100

# Add a key-value pair to empty dictionary in python
sample_dict[new_key] = new_value

It will add a new key-value pair to the dictionary. Content of the dictionary will be,

{'John': 100}

Checkout complete example where we will add multiple key-value pairs to an empty dictionary using the [] operator.

# Creating an empty dictionary
sample_dict = {}

sample_dict['John'] = 100
sample_dict['Mark'] = 101
sample_dict['Aadi'] = 102

print(sample_dict)

Output:

{'John': 100,
 'Mark': 101,
 'Aadi': 102 }

Add key-value pairs to the empty dictionary using update()

Dictionary class provides a function update(), which accepts an iterable sequence of key-value pairs and adds them to the dictionary. We can use them to add single or multiple key-value pairs to a dictionary. For example,

# Empty dictionary
sample_dict = {}

new_key = 'John'
new_value = 100

# Add a key-value pair to empty dictionary in python
sample_dict.update({new_key: new_value})

print(sample_dict)

Output:

{'John': 100}

Add key-value pairs to the empty dictionary using dictionary comprehension.

Suppose we have two lists. One list contains some strings, and another one is a list of integers. We want to add multiple key-value pairs to an empty dictionary based on the data in these two lists.
Strings in the first list should be used as keys, whereas ints in the second list should be used as values while adding the key-value pairs in the dictionary. Let’s see how to do that using dictionary comprehension in a single line i.e.

# Empty dictionary
sample_dict = {}

keys    = ['John', 'Mark', 'Aadi']
values  = [100, 200, 300]

sample_dict = { key : value 
                for key, value in zip(keys, values) }

print(sample_dict)

Output:

{'John': 100,
 'Mark': 200,
 'Aadi': 300}

We iterated over two lists in parallel and inserted the values from both the lists as key-value pairs in the empty dictionary.

Summary:

Today we learned how to add key-value pairs to an empty dictionary in python.

Advertisements

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top