×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python Dictionary update() Method (with Examples)

By IncludeHelp Last updated : December 21, 2024

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.