πPython Dictionary Append
πIntroduction
Python Dictionary Append:
A Python Dictionary is a crucial data type that stores data in key-value pairs. Each key-value pair is separated by a colon : and each pair is divided by a comma ,.
For example:
python
my_dict = {“a”: “A”, “b”: “B”, “c”: “C”, “d”: “D”}
Dictionaries provide a powerful way to organize and manage data. Let’s explore how to append values to dictionary keys effectively.
πRestrictions on Dictionary Keys
Python Dictionary Append: Before learning to append elements, it’s important to understand the key rules for dictionaries:
Python Dictionary Append Unique Keys: Dictionary keys must be unique. If a duplicate key is defined, the last declared value will overwrite the previous one.
python
my_dict = {“Name”: “ABC”, “Address”: “Mumbai”, “Age”: 30, “Name”: “XYZ”}
print(my_dict)
# Output: {‘Name’: ‘XYZ’, ‘Address’: ‘Mumbai’, ‘Age’: 30}
- Allowed Data Types for Keys:
- Keys can be numbers, strings, floats, booleans, tuples, and even built-in objects like classes and functions.
- Keys cannot be defined using mutable data types like lists.
python
my_dict = {bin: “001”, hex: “6”, 10: “ten”, bool: “1”, float: “12.8”, int: 1, False: “0”}
print(my_dict)
β Incorrect Example:
python
my_dict = {[“Name”]: “ABC”} # This will raise an error
πHow to Append Elements to a Dictionary Key in Python
Python Dictionary Append: Python’s .append() method allows you to add elements to list-type values inside a dictionary. Here’s how you can do it:
πExample: Append Elements Using .append()
Consider the following dictionary:
python
my_dict = {“Name”: [], “Address”: [], “Age”: []}
πAppending Values to Dictionary Keys
python
my_dict[“Name”].append(“Software Moji”)
my_dict[“Address”].append(“Mumbai”)
my_dict[“Age”].append(30)
print(my_dict)
πOutput:
bash
{‘Name’: [‘Software Moji’], ‘Address’: [‘Mumbai’], ‘Age’: [30]}
πAccessing Elements in a Python Dictionary
To access values in a dictionary, use square brackets with the key inside.
πExample: Access Dictionary Elements
python
my_dict = {“username”: “XYZ”, “email”: “xyz@gmail.com”, “location”: “Mumbai”}
print(“username:”, my_dict[‘username’])
print(“email:”, my_dict[’email’])
print(“location:”, my_dict[‘location’])
πOutput:
makefile
username: XYZ
email: xyz@gmail.com
location: Mumbai
πHandling Key Errors in Python Dictionary
If you attempt to access a key that does not exist, Python will raise a KeyError.
πExample: KeyError Handling
python
my_dict = {“username”: “XYZ”, “email”: “xyz@gmail.com”, “location”: “Mumbai”}
try:
print(“name:”, my_dict[‘name’])
except KeyError:
print(“Key not found in dictionary.”)
πOutput:
pgsql
Key not found in dictionary.
πBest Practices for Appending in Dictionaries
β
Always initialize dictionary keys with list values if you plan to append data.
β
Use .get() to safely access dictionary keys without risking KeyError.
πExample: Using .get() for Safe Access
python
my_dict = {“Name”: [“Alice”], “Age”: [25]}
# Append safely using `.get()` method
my_dict.get(“Name”, []).append(“Bob”)
print(my_dict)
# Output: {‘Name’: [‘Alice’, ‘Bob’], ‘Age’: [25]}