Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Python Dictionaries: Adding, Updating, and Managing Key/Value Pairs

Python dictionaries are foundational data structures that store data as key/value pairs. Keys are immutable and unique, while values can be any data type, including nested structures.

Key Rules for Dictionary Keys

Adding Elements to a Dictionary

To add a new key/value pair, simply assign a value to a new key:

my_dict = {"username": "XYZ", "email": "xyz@example.com"}
my_dict["location"] = "Mumbai"
print(my_dict)

Output: {"username": "XYZ", "email": "xyz@example.com", "location": "Mumbai"}

When the value is a list, you can append items to that list:

my_dict = {"tags": []}
my_dict["tags"].append("python")
print(my_dict)

Output: {"tags": ["python"]}

Accessing Dictionary Elements

Retrieve a value by its key using square brackets. If the key does not exist, a KeyError is raised:

print(my_dict["username"])  # XYZ
print(my_dict["nonexistent"])  # KeyError

To avoid errors, use dict.get() or dict.setdefault():

print(my_dict.get("nonexistent", "default"))

Deleting Elements

Updating Existing Values

Assign a new value to an existing key to update it:

my_dict["username"] = "ABC"
print(my_dict)

Combining Dictionaries

Merge two dictionaries using update() or the union operator (|) in Python 3.9+:

dict_a = {"a": 1, "b": 2}
dict_b = {"b": 3, "c": 4}
dict_a.update(dict_b)
print(dict_a)  # {"a": 1, "b": 3, "c": 4}

# or
combined = dict_a | dict_b
print(combined)

Embedding a Dictionary Inside Another

Assign a whole dictionary to a new key to nest it:

parent = {"username": "XYZ"}
child = {"firstName": "Nick", "lastName": "Price"}
parent["name"] = child
print(parent)

Output: {"username": "XYZ", "name": {"firstName": "Nick", "lastName": "Price"}}

Summary

For more details, refer to the official Python documentation: Python Data Structures – Dictionaries.

Python

  1. Getting Started with Python: Install, Run, and Write Your First Program
  2. Python Variables, Constants, and Literals – A Comprehensive Guide
  3. Mastering Python Dictionaries: Creation, Manipulation, and Advanced Techniques
  4. Retrieve Current Date and Time in Python: A Practical Guide
  5. Python Print() Function: A Practical Guide with Examples
  6. Calculating Averages in Python: A Practical Guide
  7. Avoiding Common Pitfalls: Proper Exception Handling in Python
  8. Mastering Brand Equity: A Strategic Blueprint for Sustainable Business Value
  9. Python Dictionary Fundamentals: Keys, Values, and Access
  10. Unlocking Business Value with UID: Enhancing Asset Tracking & Compliance