Add Key-Value Pairs to a Dictionary in Python
In Python, you can add key-value pairs to a dictionary using the following methods:
(1) Using square brackets []
You can add a key-value pair to a dictionary by assigning a value to a new key using square brackets.
For example:
# Creating an empty dictionary
person = {}
# Adding key-value pairs
person["name"] = "James"
person["age"] = 35
print(person) # Output: {'name': 'James', 'age': 35}
If the key already exists, its value will be updated.
person = {"name": "James", "age": 35}
person["age"] = 50
print(person) # Output: {'name': 'James', 'age': 50}
(2) Using update() method
The update()
method allows you to add multiple key-value pairs to a dictionary at once by passing another dictionary or an iterable of key-value pairs.
For example:
person = {"name": "James"}
person.update({"age": 35, "city": "New York"})
print(person) # Output: {'name': 'James', 'age': 35, 'city': 'New York'}
If a key already exists, its value is updated; otherwise, a new key-value pair is added to the dictionary.
For example:
person = {"name": "James", "age": 35}
person.update({"age": 50, "city": "New York"})
print(person) # Output: {'name': 'James', 'age': 50, 'city': 'New York'}
(3) Using setdefault() method
The setdefault()
method adds a key with a default value only if the key doesn’t already exist, and returns that value. If the key already exists, it returns the current value without modifying the dictionary.
For example:
person = {"name": "James", "age": 35}
age = person.setdefault("age", 50)
print(age) # Output: 35
city = person.setdefault("city", "New York")
print(city) # Output: New York
print(person) # Output: {'name': 'James', 'age': 35, 'city': 'New York'}
Choosing the right method
Use []
for adding a single key-value pair.
Use update()
method for adding multiple key-value pairs at once.
Use setdefault()
method to add a key-value pair only if the key doesn’t exist.