Python Add Dictionary Items

Introduction

Adding items to a Python dictionary means inserting new key-value pairs. Dictionaries are mutable, so you can add items by assigning a new key or by using the update() method to add multiple items at once. This tutorial explains these methods with examples.

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

Ways to Add Items to Dictionary

  • Add single item by assigning a new key
  • Add multiple items using update() method
  • नई key assign करके एक आइटम जोड़ना
  • update() method से एक साथ कई आइटम जोड़ना
Example 1: Add Single Item by Assignment
my_dict = {'name': 'Sita', 'age': 28}
my_dict['city'] = 'Jaipur'
print(my_dict)

Add a new key 'city' with value 'Jaipur' by simple assignment.

सरल assignment से नई key 'city' और value 'Jaipur' जोड़ें।

Output:

{'name': 'Sita', 'age': 28, 'city': 'Jaipur'}
Example 2: Add Multiple Items Using update()
my_dict = {'name': 'Sita', 'age': 28}
my_dict.update({'city': 'Jaipur', 'profession': 'Teacher'})
print(my_dict)

Use update() to add multiple new items at once.

<code>update()</code> method से एक साथ कई नई items जोड़ें।

Output:

{'name': 'Sita', 'age': 28, 'city': 'Jaipur', 'profession': 'Teacher'}
Example 3: Add Item with Existing Key Overwrites Value
my_dict = {'name': 'Sita', 'age': 28}
my_dict['age'] = 29
print(my_dict)

If the key exists, adding with assignment will overwrite the old value.

अगर key पहले से मौजूद है, तो assignment से value overwrite हो जाएगी।

Output:

{'name': 'Sita', 'age': 29}