Python Add To Dictionary

Python-Add-To-Dictionary-ipcisco-1

In this lesson, we will learn Python Add to Dictionary methods. We will do different coding examples like python dictionary add and python dictionary append. We can use these fucntions to add a new item to the dictionary. So, let’s see the example of the usage of this functions.

 

Firstly, let’s change the value of a key:pair value.

 

device ={
  "vendor": "Cisco",
  "model": "9000 series",
  "RU": 44
}
device["model"] = "4000 series"
print(device)

 

The output of this python code will be:

 

{'vendor': 'Cisco', 'model': '4000 series', 'RU': 44}

 

Python-Add-To-Dictionary-ipcisco-1

 


 

Append Method

 

We can also sue the below code to add values to the existing python dictionary. This can be used as python dictionary append. Normally there is no append method of python dictionaries.

 

device = {"vendor":["Cisco"],"model":["9000 series"],"RU":[44]};
device["model"].append("4000 series")
device["RU"].append(30)          
print(device)

 

{'vendor': ['Cisco'], 'model': ['9000 series', '4000 series'], 'RU': [44, 30]}

 

Python-Add-To-Dictionary-ipcisco-2

 

In the below example, agian we will change the key:pair value of the dictionary.

 

character = {"race":["dwarf"],"name":["Gimli", "Balin"],"role":["warrior"]};
character["race"].append("elf")
character["name"].append("legolas")
print(character)

 

{'race': ['dwarf', 'elf'], 'name': ['Gimli', 'Balin', 'legolas'], 'role': ['warrior']}

 

Update Method

 

We can use update method to add  or change the values of a key:valu pair.

 

device ={
  "vendor": "Cisco",
  "model": "9000 series",
  "RU": 44
}
device.update({"RU": 30})
print(device)

 

The output of this python code will be like below:

 

{'vendor': 'Cisco', 'model': '9000 series', 'RU': 30}

how-to-add-To-Dictionary-in-python

Update method can get only one attribute. If you use one more attribute, it will give an error as output. To update one more key:pair, we should use differenet update lines.

 

Let’s do another example with python dictionary update method and change all the key:value pairs in the dictionary.

 

device ={
  "vendor": "Cisco",
  "model": "9000 series",
  "RU": 44
}
device.update({"vendor": "Nokia"})
device.update({"model": "7950 XRS"})
device.update({"RU": "39"})
print(device)

 

The output of this python code will be:

 

{'vendor': 'Nokia', 'model': '7950 XRS', 'RU': '39'}

 

Here, we have learned the methods that we can add items to the python dictionaries. You can use these python dictionary add methods on your various code examples. You can do different coding exaamples o this lesson. More practice will give you more experience on such methods.

Back to: Python Programming Course > Python Dictionaries

Leave a Reply

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

Contact

  • info@ipcisco.com
IPCisco is the Winner! “Best Certification Study Journey of 2019!”

Cisco-ITBlogAwards-2019-Winner-IPCisco-k