Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Add Elements to a Dictionary
Python dictionaries are versatile data structures that store data as key-value pairs. Adding elements to dictionaries is a common operation with several approaches, each suited for different scenarios.
What is a Python Dictionary?
A dictionary in Python stores key-value pairs, where each key must be unique and immutable (strings, integers, tuples). Values can be of any data type and may be repeated.
Syntax
{key1: value1, key2: value2, key3: value3}
Example
# Creating a simple dictionary
student = {'name': 'Alice', 'age': 20, 'grade': 'A'}
print(student)
{'name': 'Alice', 'age': 20, 'grade': 'A'}
Method 1: Using Square Bracket Notation
The simplest way to add a single key-value pair to a dictionary ?
student = {'name': 'Alice', 'age': 20}
print("Original dictionary:", student)
# Adding a new key-value pair
student['grade'] = 'A'
print("After adding grade:", student)
# Adding another element
student['subject'] = 'Python'
print("After adding subject:", student)
Original dictionary: {'name': 'Alice', 'age': 20}
After adding grade: {'name': 'Alice', 'age': 20, 'grade': 'A'}
After adding subject: {'name': 'Alice', 'age': 20, 'grade': 'A', 'subject': 'Python'}
Method 2: Using the update() Method
The update() method is ideal for adding multiple key-value pairs at once ?
Syntax
dict.update([other])
Example
student = {'name': 'Alice', 'age': 20}
print("Original dictionary:", student)
# Adding single key-value pair
student.update({'grade': 'A'})
print("After update with single pair:", student)
# Adding multiple key-value pairs
additional_info = {'subject': 'Python', 'semester': 2}
student.update(additional_info)
print("After update with multiple pairs:", student)
Original dictionary: {'name': 'Alice', 'age': 20}
After update with single pair: {'name': 'Alice', 'age': 20, 'grade': 'A'}
After update with multiple pairs: {'name': 'Alice', 'age': 20, 'grade': 'A', 'subject': 'Python', 'semester': 2}
Method 3: Using enumerate() with For Loop
This method is useful when adding elements from a list with index-based keys ?
student = {'name': 'Alice', 'age': 20}
subjects = ['Math', 'Science', 'History']
print("Original dictionary:", student)
for index, subject in enumerate(subjects):
student[f'subject_{index}'] = subject
print("After adding subjects:", student)
Original dictionary: {'name': 'Alice', 'age': 20}
After adding subjects: {'name': 'Alice', 'age': 20, 'subject_0': 'Math', 'subject_1': 'Science', 'subject_2': 'History'}
Method 4: Using zip() Method
The zip() function combines two lists to create key-value pairs ?
student = {}
keys = ['name', 'age', 'grade']
values = ['Bob', 22, 'B']
for key, value in zip(keys, values):
student[key] = value
print("Dictionary created using zip:", student)
Dictionary created using zip: {'name': 'Bob', 'age': 22, 'grade': 'B'}
Method 5: Using Conditional Check
This method prevents overwriting existing keys ?
student = {'name': 'Alice', 'age': 20, 'grade': 'A'}
# Try to add a new key
if 'subject' not in student:
student['subject'] = 'Python'
print("Added new subject:", student)
else:
print("Subject key already exists")
# Try to add an existing key
if 'age' not in student:
student['age'] = 25
else:
print("Age key already exists, not overwritten")
print("Final dictionary:", student)
Added new subject: {'name': 'Alice', 'age': 20, 'grade': 'A', 'subject': 'Python'}
Age key already exists, not overwritten
Final dictionary: {'name': 'Alice', 'age': 20, 'grade': 'A', 'subject': 'Python'}
Method 6: Using the ** Operator
The unpacking operator creates a new dictionary by merging existing ones ?
original = {'name': 'Alice', 'age': 20}
additional = {'grade': 'A', 'subject': 'Python'}
# Create new dictionary with merged data
merged = {**original, **additional}
print("Original dictionary:", original)
print("Additional dictionary:", additional)
print("Merged dictionary:", merged)
Original dictionary: {'name': 'Alice', 'age': 20}
Additional dictionary: {'grade': 'A', 'subject': 'Python'}
Merged dictionary: {'name': 'Alice', 'age': 20, 'grade': 'A', 'subject': 'Python'}
Comparison
| Method | Best For | Modifies Original |
|---|---|---|
Square brackets []
|
Single key-value pair | Yes |
update() |
Multiple pairs | Yes |
enumerate() |
List with index keys | Yes |
zip() |
Two separate lists | Yes |
| Conditional check | Preventing overwrites | Yes |
** operator |
Creating new dictionary | No |
Conclusion
Use square brackets for single additions, update() for multiple pairs, and the ** operator when you need a new dictionary. Choose the method based on whether you want to modify the original dictionary or create a new one.
