Python Dictionary Manipulation Examples
1. Insert an item into a dictionary
# Example 1: Insert an item
my_dict = {'name': 'Alice', 'age': 25}
my_dict['city'] = 'New York'
print(my_dict)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
2. Update an item in a dictionary
# Example 2: Update an item
my_dict = {'name': 'Alice', 'age': 25}
my_dict['age'] = 26
print(my_dict)
# Output: {'name': 'Alice', 'age': 26}
3. Delete an item from a dictionary
# Example 3: Delete an item
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
del my_dict['city']
print(my_dict)
# Output: {'name': 'Alice', 'age': 25}
4. Check if a key exists in a dictionary
# Example 4: Check if a key exists
my_dict = {'name': 'Alice', 'age': 25}
if 'age' in my_dict:
print("Key exists")
# Output: Key exists
5. Iterate over dictionary keys
# Example 5: Iterate over keys
my_dict = {'name': 'Alice', 'age': 25}
for key in my_dict:
print(key)
# Output: name, age
6. Iterate over dictionary values
# Example 6: Iterate over values
my_dict = {'name': 'Alice', 'age': 25}
for value in my_dict.values():
print(value)
# Output: Alice, 25
7. Iterate over dictionary key-value pairs
# Example 7: Iterate over key-value pairs
my_dict = {'name': 'Alice', 'age': 25}
for key, value in my_dict.items():
print(key, value)
# Output: name Alice, age 25
8. Merge two dictionaries
# Example 8: Merge two dictionaries
dict1 = {'name': 'Alice', 'age': 25}
dict2 = {'city': 'New York', 'country': 'USA'}
my_dict = {**dict1, **dict2}
print(my_dict)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}
9. Clear all items from a dictionary
# Example 9: Clear a dictionary
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
my_dict.clear()
print(my_dict)
# Output: {}
10. Get a value with a default
# Example 10: Get a value with default
my_dict = {'name': 'Alice', 'age': 25}
age = my_dict.get('age', 30)
height = my_dict.get('height', 170)
print(age, height)
# Output: 25 170