The dictionary in Python is a useful developed-in data structure that allows you to define a mapping between elements as key-value pairs. You can utilize the key to retrieve the corresponding values.
In this tutorial, we will explore how to add and update the dictionary in Python.
What is a Dictionary in Python?
The dictionary is a type of value and hash set that are stored in a key-value pair fashion. For each key in a dictionary, there is a value linked to it. We can cross-check the dictionary depending on the key.
Therefore, when the key is recognized, dictionaries are optimized to retrieve values.
List of Python Dictionary Methods
Python Dictionary Methods
Function Name | Description |
clear() | Removes all items from the dictionary, leaving it empty. |
copy() | Returns a shallow copy of the dictionary. |
from keys(iterable, value) | Creates a new dictionary with keys from an iterable and assigns a default value. |
get(key, default) | Retrieves the value for a given key; returns default if the key is not found. |
items() | Returns a view object with all key-value pairs as tuples. |
keys() | Returns a view object containing all dictionary keys in insertion order. |
pop(key, default) | Removes and returns the value for the given key; raises an error if the key is missing (unless a default is provided). |
popitem() | Removes and returns the last inserted key-value pair as a tuple (useful for LIFO operations). |
setdefault(key, default) | Returns the value of a key; if the key does not exist, insert it with the given default value. |
values() | Returns a view object with all values from the dictionary. |
update(iterable or dict) | Updates the dictionary with key-value pairs from another dictionary or an iterable. |
How to create a Dictionary in Python?
To create a dictionary, you need to initialize a variable with empty curly braces.
Steps to Add an Item to a Dictionary
Step 1: Create an empty dictionary or use an existing one.
Python
CopyEdit
my_dict = {} # Empty dictionary
Step 2: Add a new key-value pair using assignment (=).
CopyEdit
my_dict[“name”] = “Alice”
my_dict[1] = 100
Step 3: Use the update() method to add multiple key-value pairs at once.
Python
CopyEdit
my_dict.update({“age”: 25, “city”: “New York”})
Example after adding items:
Python
CopyEdit
print(my_dict)
# Output: {‘name’: ‘Alice’, 1: 100, ‘age’: 25, ‘city’: ‘New York’}
How to update Dictionary in Python?
Now let’s check out how you can update Dictionary in Python
Step 1: Using Assignment (=) You can update a dictionary by directly assigning a new value to an existing key.
python Copy Edit my_dict = {“name”: “Alice”, “age”: 25, “city”: “New York”}
Updating an existing key
my_dict[“age”] = 26
my_dict[“city”] = “Los Angeles”
print(my_dict)
Step 2: Using update () Method
The update () method allows you to update multiple key-value pairs at once.
Python
my_dict.update({“age”: 27, “country”: “USA”}) # Adds “country” and updates “age”
print(my_dict)
# Output: {‘name’: ‘Alice’, ‘age’: 27, ‘city’: ‘Los Angeles’, ‘country’: ‘USA’}
Step 3: Utilising a Loop to update different keys
Updates: {“age”30, “city”: San Fransicp}
for key, value in updates. Items ():
my_
my_dict[key] = value
print(my_dict)
# Output: {‘name’: ‘Alice’, ‘age’: 30, ‘city’: ‘San Francisco’, ‘country’: ‘USA’}
Step 4: Updating a Dictionary with Another Dictionary
You can merge two dictionaries, where existing keys get updates, and new keys are added.
dict1= {“a”:1, “b”:2}
dict2= {“b”3, “c”:4
dict1 = {“a”: 1, “b”: 2}{“b”3, “c”:4
dict2 = {“b”: 3, “c”: 4}
dict1.update(dict2)
print(dict1)
# Output: {‘a’: 1, ‘b’: 3, ‘c’: 4}
Step 5: By utilizing Dictionary Comprehension
If you want to update values depending on the condition, you can utilize dictionary comprehension.
python copy Edit my_dict = {1:10:2:20: 3: 30}
Multiply each value by 2
my_dict= {key: value X 2 for key, value in my_dict.items ()}
print (my_dict)
Output: {1:20, 2:40, 3:60}
Summing UP
By following the above-mentioned steps you can easily add and update a dictionary in Python. Moreover, you can explore the module collections, that offer alternatives like counter and defaulted for more advanced dictionary operations.
Moreover, merging dictionaries, using loops, or applying dictionary comprehensions can provide more advanced update methods. With its flexibility and efficiency, Python’s dictionary is a powerful data structure for managing and manipulating data dynamically.
Frequently Asked Questions
Q 1. How do you update a dictionary in Python?
Ans. Use direct assignment (dict[key] = value) or the update() method.
my_dict[“age”] = 26
my_dict.update({“city”: “New York”})
Q 2. How do you update two dictionaries in Python?
Ans. Use update() or the |= operator (Python 3.9+).
dict1.update(dict2) # Merges dict2 into dict1
dict1 |= dict2 # Alternative (Python 3.9+)
Q 3. How do you update a dictionary in a loop in Python?
Ans. Loop through the dictionary and modify values.
for key in my_dict:
my_dict[key] += 10
Q 4. How to append a dictionary in Python?
Ans. Use assignment to add new key-value pairs.
my_dict[“new_key”] = “value”
Q 5. How to add two lists in Python?
Use the + operator or extend().
list1 + list2 # Returns a new combined list
list1.extend(list2) # Modifies list1 in place
Q 6. How to add to a set in Python?
Ans. Use add() for a single item or update() for multiple.
my_set.add(10)
my_set.update([20, 30, 40])