Python Dictionary update() Method (with Examples)

Python Dictionary update() Method: In this tutorial, we will learn about the update() method of a dictionary with its usage, syntax, parameters, return type, and examples. By IncludeHelp Last updated : June 12, 2023

Python Dictionary update() Method

The update() is an inbuilt method of dict class that is used to update the dictionary by inserting new items to the dictionary. The method is called with this dictionary and returns nothing.

Syntax

The following is the syntax of update() method:

dictionary_name.setdefault(iterable)

Parameter(s):

The following are the parameter(s):

  • iterable – It represents an iterbale object or a dictionary to be inserted in the dictionary.

Return Value

The return type of this method <class 'NoneType'>, it returns nothing.

Example 1: Use of Dictionary update() Method

alphabets = {
    "a": "Apple", 
    "b": "Bat", 
    "c": "Cat"
}

alphabets.update({"d" : "Dog"})

print("alphabets:", alphabets)

Output

alphabets: {'a': 'Apple', 'b': 'Bat', 'c': 'Cat', 'd': 'Dog'}

Example 2: Use of Dictionary update() Method

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# inserting an item
student.update({'city' : 'Indore'})

# printing dictionary after update()
print("data of student dictionary after update()...")
print(student)

# inserting multiple items
student.update({'city' : 'Indore', 'address' : 'Tech park'})

# printing dictionary after update()
print("data of student dictionary after update()...")
print(student)

Output

data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5}
data of student dictionary after update()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'city': 'Indore'}
data of student dictionary after update()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'city': 'Indore', 'address': 'Tech park'}

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.