Junior
What operations can be performed with mappings (dictionaries) in Python?
sobes.tech AI
Answer from AI
- Access by key
- Assigning by key
- Deletion by key
- Iteration over keys
- Getting all keys, values, key-value pairs
- Checking for key existence
- Merging dictionaries
- Creating dictionaries from sequences or other dictionaries
- Copying dictionaries
# Accessing value by key
my_dict = {"a": 1, "b": 2}
value = my_dict["a"] # value is now 1
# Assigning value by key
my_dict["c"] = 3 # my_dict becomes {"a": 1, "b": 2, "c": 3}
# Deleting element by key
del my_dict["b"] # my_dict becomes {"a": 1, "c": 3}
# Iterating over keys
for key in my_dict:
print(key) # Prints "a", then "c"
# Getting list of all keys
keys = my_dict.keys() # Gets dict_keys(['a', 'c'])
# Getting list of all values
values = my_dict.values() # Gets dict_values([1, 3])
# Getting list of all key-value pairs (tuples)
items = my_dict.items() # Gets dict_items([('a', 1), ('c', 3)])
# Checking for key presence
is_present = "a" in my_dict # is_present is now True
# Merging dictionaries (Python 3.9+)
dict1 = {"x": 10}
dict2 = {"y": 20}
merged_dict = dict1 | dict2 # merged_dict becomes {"x": 10, "y": 20}
# Creating dictionary from list of pairs (tuples)
list_of_tuples = [('z', 30), ('w', 40)]
new_dict = dict(list_of_tuples) # new_dict becomes {'z': 30, 'w': 40}
# Copying dictionary
copied_dict = my_dict.copy() # Creates a shallow copy of my_dict