Python – Append Multitype Values in Dictionary
There are cases where we may want to append multiple types of values, such as integers, strings or lists to a single dictionary key. For example, if we are creating a dictionary to store multiple types of data under the same key, such as user details (e.g., age, address, and hobbies), we need to handle these values efficiently. Let’s explore various methods to append multitype values to a dictionary key.
Using list with Direct Assignment
This method involves using a list to store multiple values under a dictionary key.
# Initialize a dictionary
d = {"user1": [25, "New York"]}
# Append multiple values to a key
d["user1"].append("Reading")
# Print the dictionary
print(d)
Output
{'user1': [25, 'New York', 'Reading']}
Explanation:
- A dictionary is initialized with a key “user1” whose value is a list containing multiple types of data.
- append method adds the new value “Reading” to the existing list.
- This method efficiently handles appending new values while maintaining the existing data.
Using defaultdict() from collections
defaultdict() simplifies appending values by automatically initializing an empty list for missing keys.
from collections import defaultdict
# Initialize a defaultdict
d = defaultdict(list)
# Append values to a key
d["user1"].append(25)
d["user1"].append("New York")
d["user1"].append("Reading")
# Print the dictionary
print(dict(d))
Output
{'user1': [25, 'New York', 'Reading']}
Explanation:
- defaultdict() ensures that a new key automatically gets an empty list as its value, avoiding the need for manual initialization.
- Multiple values of different types are appended to the same key without additional checks.
Using setdefault()
setdefault() method initializes a key with a default value if it does not already exist.
# Initialize a dictionary
d = {}
# Append values to a key
d.setdefault("user1", []).append(25)
d.setdefault("user1", []).append("New York")
d.setdefault("user1", []).append("Reading")
# Print the dictionary
print(d)
Output
{'user1': [25, 'New York', 'Reading']}
Explanation:
- setdefault() method ensures that the key “user1” is initialized with an empty list if it doesn’t exist.
- New values are then appended to the list associated with the key.
Using Manual Initialization
This approach involves manually checking if a key exists and initializing it before appending values.
# Initialize a dictionary
d = {}
# Check if key exists and append values
if "user1" not in d:
d["user1"] = []
d["user1"].append(25)
d["user1"].append("New York")
d["user1"].append("Reading")
# Print the dictionary
print(d)
Output
{'user1': [25, 'New York', 'Reading']}
Explanation:
- The code explicitly checks if the key “user1” exists in the dictionary.
- If the key does not exist, it is initialized with an empty list before appending values.