Add a key value pair to dictionary in Python

PythonServer Side ProgrammingProgramming

Python dictionaries are an unordered collection of key value pairs. In this tutorial we will see how we can add new key value pairs to an already defined dictionary. Below are the two approaches which we can use.

Assigning a new key as subscript

We add a new element to the dictionary by using a new key as a subscript and assigning it a value.

Example

CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1}
print(CountryCodeDict)
CountryCodeDict["Spain"]= 34
print "After adding"
print(CountryCodeDict)

Output

Running the above code gives us the following result −

{'India': 91, 'USA': 1, 'UK': 44}
After adding
{'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}

Using the update() method

The update method directly takes a key-value pair and puts it into the existing dictionary. The key value pair is the argument to the update function. We can also supply multiple key values as shown below.

Example

CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1, "Spain" : 34}
print(CountryCodeDict)

CountryCodeDict.update( {'Germany' : 49} )

print(CountryCodeDict)

# Adding multiple key value pairs
CountryCodeDict.update( [('Austria', 43),('Russia',7)] )

print(CountryCodeDict)

Output

Running the above code gives us the following result −

{'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}
{'Germany': 49, 'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}
{'USA': 1, 'India': 91, 'Austria': 43, 'Germany': 49, 'UK': 44, 'Russia': 7, 'Spain': 34}

By merging two dictionaries

We can also append elements to a dictionary by merging two dictionaries. Here again, we use the update() method but the argument to the method is a dictionary itself.

Example

CountryCodeDict1 = {"India": 91, "UK" : 44 , "USA" : 1, "Spain" : 34}
CountryCodeDict2 = {"Germany": 49, "Russia" : 7 , "Austria" : 43}
CountryCodeDict1.update(CountryCodeDict2)
print(CountryCodeDict1)

Output

Running the above code gives us the following result −

{'Austria': 43, 'Germany': 49, 'UK': 44, 'USA': 1, 'India': 91, 'Russia': 7, 'Spain': 34}
raja
Published on 08-Jul-2019 14:46:41
Advertisements