StudyLover
  • Home
  • Study Zone
  • Profiles
  • Contact us
  • Sign in
StudyLover Replace values
Download
  1. Python
  2. Problem Solving: Lists, Dictionaries, and Function-Based Design
Accessing Keys : Traversing Dictionaries
Problem Solving: Lists, Dictionaries, and Function-Based Design

Replace values

To replace values in a dictionary, you can use the following methods:

1. Direct assignment:

Python

my_dict = {"name": "Alice", "age": 30}

my_dict["age"] = 31

print(my_dict)  # Output: {'name': 'Alice', 'age': 31}

2. update() method:

Python

my_dict = {"name": "Alice", "age": 30}

my_dict.update({"age": 31})

print(my_dict)  # Output: {'name': 'Alice', 'age': 31}

Key points:

  • Both methods directly modify the existing dictionary.

  • The update() method can be used to replace multiple values at once.

  • If the key doesn't exist, using direct assignment will create a new key-value pair, while update() will overwrite the existing value.

Example:

Python

person = {"name": "John", "age": 35, "city": "New York"}

 

# Replace the value for "age"

person["age"] = 32

 

# Replace multiple values using update()

person.update({"city": "Los Angeles", "occupation": "Engineer"})

 

print(person)  # Output: {'name': 'John', 'age': 32, 'city': 'Los Angeles', 'occupation': 'Engineer'}

By understanding these methods, you can effectively replace values in dictionaries to update your data.

 

Accessing Keys Traversing Dictionaries
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website