Python Change Dictionary Items

Introduction

Changing dictionary items in Python involves modifying the value of existing keys or adding new key-value pairs. Dictionaries are mutable, so you can update them easily using assignment or built-in methods like update(). This tutorial explains all ways to change dictionary contents with examples.

Python में dictionary items को बदलना मतलब पहले से मौजूद keys की value को modify करना या नई key-value जोड़े जोड़ना है। Dictionaries mutable होती हैं, इसलिए आप इन्हें आसानी से assignment या built-in methods जैसे update() से बदल सकते हैं। इस ट्यूटोरियल में dictionary में बदलाव के सभी तरीकों को उदाहरणों के साथ समझाया गया है।

Ways to Change Dictionary Items

  • Modify value of an existing key using assignment
  • Add a new key-value pair using assignment
  • Use update() method to add or update multiple items
  • Assignment से किसी मौजूदा key की value बदलना
  • Assignment से नई key-value जोड़ना
  • update() method से एक साथ कई items जोड़ना या बदलना
Example 1: Modify Existing Key's Value
my_dict = {'name': 'Rahul', 'age': 22}
my_dict['age'] = 23
print(my_dict)

Change the value of existing key 'age' from 22 to 23 using assignment.

Assignment से 'age' key की value 22 से 23 में बदलें।

Output:

{'name': 'Rahul', 'age': 23}
Example 2: Add New Key-Value Pair
my_dict = {'name': 'Rahul', 'age': 22}
my_dict['city'] = 'Delhi'
print(my_dict)

Add a new key 'city' with value 'Delhi' using assignment.

Assignment से नई key 'city' और value 'Delhi' जोड़ें।

Output:

{'name': 'Rahul', 'age': 22, 'city': 'Delhi'}
Example 3: Update Multiple Items Using update()
my_dict = {'name': 'Rahul', 'age': 22}
my_dict.update({'age': 24, 'city': 'Mumbai'})
print(my_dict)

Use update() to modify 'age' to 24 and add new key 'city'.

update() method से 'age' को 24 करें और नई key 'city' जोड़ें।

Output:

{'name': 'Rahul', 'age': 24, 'city': 'Mumbai'}