python

How to add keys and values to a dictionary in Python

In this tutorial, we are going to see how to add keys and values to a dictionary in Python. Dictionary in Python is an unordered collection of values, which maps one set of objects(keys) to another set of objects(values) unlike other data types containing only one value as an element.

When using a dictionary, it is sometimes necessary to add or modify the key or value. In this tutorial, we are going to see how to add keys and values to a dictionary in Python.
 

 

How to add keys and values to a dictionary

update() function in Python allows you to add items to a dictionary if the key is not in the dictionary. If the key is in the dictionary, it updates the key with the new value.

# Dictionary of languages
languages_dic = {
    "Python": 55,
    "Java" : 142,
    "PHP" : 32,
    "C" : 13,
}
# Adding a new key-value pair
languages_dic.update( {'C++' : 24} )
#Display the update 
print(languages_dic)

Output:

{'C++': 24, 'PHP': 32, 'Python': 55, 'C': 13, 'Java': 142}
 

Update the value of an existing key in the dictionary

If we call the update() function with a key/value and the key already exists in the dictionary, its value will be updated with the new value. In the code below, we will update the value of the key ‘Python’:

# Dictionary of languages
languages_dic = {
    "Python": 55,
    "Java" : 142,
    "PHP" : 32,
    "C" : 13,
}
# Updating the value
languages_dic.update(Python = 70)
#Display the update 
print(languages_dic)

Output:

{'Python': 70, 'PHP': 32, 'Java': 142, 'C': 13}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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