![]() |
Dictionaries in Python are versatile data structures that allow you to store and manage key-value pairs. One common challenge when working with dictionaries is how to add new key-value pairs without overwriting existing ones. In this article, we’ll explore five simple and commonly used methods to achieve this in Python Python Add to Dictionary Without OverwritingBelow, are the examples of how to Python add to Dictionary Without Overwriting.
Add to Dictionary using AssignmentIn this example, the below code creates a dictionary `existing_dict` with ‘name’ and ‘age’ keys. It then adds ‘city: New York’ and updates ‘age’ to 26. The final dictionary is printed, showing the changes. Python3
Output
{'name': 'John', 'age': 26, 'city': 'New York'} Using
|
existing_dict = { 'name' : 'John' , 'age' : 25 } new_data = { 'city' : 'New York' , 'age' : 26 } existing_dict.update(new_data) print (existing_dict) |
{'name': 'John', 'age': 26, 'city': 'New York'}
setdefault()
MethodIn this example , below code uses `setdefault()` to add ‘city: New York’ to the dictionary `existing_dict` only if ‘city’ is not already a key. It also attempts to set the ‘age’ key to 26, but this has no effect as the key already exists.
existing_dict = { 'name' : 'John' , 'age' : 25 } existing_dict.setdefault( 'city' , 'New York' ) existing_dict.setdefault( 'age' , 26 ) print (existing_dict) |
{'name': 'John', 'age': 25, 'city': 'New York'}
**
Unpacking OperatorIn this example, below code merges two dictionaries, `existing_dict` and `new_data`, using the `**` unpacking operator. It creates a new dictionary `merged_dict` containing the combined key-value pairs. The resulting dictionary is then printed, illustrating the merged data.
existing_dict = { 'name' : 'John' , 'age' : 25 } new_data = { 'city' : 'New York' , 'age' : 26 } merged_dict = { * * existing_dict, * * new_data} print (merged_dict) |
{'name': 'John', 'age': 26, 'city': 'New York'}
In conclusion above, methods provide simple and effective ways to add key-value pairs to a dictionary in Python without overwriting existing entries. Depending on your specific use case, you can choose the method that best fits your needs. Whether it’s using update()
, setdefault()
, dict.update()
, the **
unpacking operator, Python offers multiple approaches to handle dictionary updates efficiently.
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |