A dictionary is an unordered collection of key-value pairs. Keys are unique and immutable, while values can be of any type and can be modified.
Characteristics of dictionaries:
- Unique Keys: Each key in a dictionary is unique, meaning there cannot be duplicate keys
- Value Mutability: The values in a dictionary can be modified after creation
- Unordered: Although dictionaries maintain insertion order from Python 3.7 onwards, you should not rely on the order
If you want to learn more, check out the Introduction to Programming Course
Creating a dictionary
Dictionaries in Python are defined using curly braces {} and key-value pairs are separated by a colon :. For example, the syntax would be like this,
my_dictionary = {
"key1": value1,
"key2": value2,
"key3": value3
}
Where key1, key2 and key3 are the keys that will be used to access the corresponding values.
For example, like this.
my_dictionary = {"name": "Luis", "height": 30, "profession": "Engineer"}
In this example, my_dictionary is a dictionary with three key-value pairs: - name with the value “Luis”
agewith the value 30professionwith the value “Ingeniero”
Operations with dictionaries
Accessing elements
To access the values of a dictionary, the corresponding key is used as follows:
print(my_dictionary["name"]) # Result: Luis
print(my_dictionary["age"]) # Result: 30
Modifying elements
To modify a dictionary, you simply assign a new value to an existing key or add a new key-value pair as follows:
my_dictionary["key1"] = new_value
my_dictionary["new_key"] = new_value
Adding elements
To add a new key-value pair to a dictionary in Python, you can use the syntax my_dictionary["new_key"] = new_value.
my_dictionary["city"] = "Madrid" # Adds a new key-value pair
If the key already exists in the dictionary, the associated value will be overwritten with the new provided value (as we saw in the previous section).
Checking key membership
To check if a key is present in a dictionary, you can use the in expression. This expression returns True if the key is present in the dictionary and False if it is not.
if "name" in my_dictionary:
print("The key 'name' is present in the dictionary.")
Getting keys and values
The items() method returns a view of the dictionary’s key-value pairs in the form of tuples.
my_dictionary = {"name": "Luis", "age": 30, "city": "Madrid"}
view_items = my_dictionary.items() # Returns a view of the key-value pairs
print(view_items) # Result: dict_items([('name', 'Luis'), ('age', 30), ('city', 'Madrid')])
On the other hand, we also have the methods:
keys()returns a list of all the keys in the dictionaryvalues()returns a list of all the values
keys = my_dictionary.keys() # Returns a list of the keys
values = my_dictionary.values() # Returns a list of the values
Shallow copy of the dictionary
The copy() method returns a shallow copy of the dictionary. This means a new dictionary instance is created containing the same key-value pairs as the original dictionary.
my_dictionary = {"name": "Luis", "age": 30, "city": "Madrid"}
copy_dictionary = my_dictionary.copy() # Creates a shallow copy of the dictionary
print(copy_dictionary) # Result: {"name": "Luis", "age": 30, "city": "Madrid"}
Be careful, the copy is shallow. If the dictionary values are references, the values in the copy will point to the same objects.
Removing elements
There are several ways to remove elements from a dictionary in Python. You can use the del statement followed by the key name to delete the key and its corresponding value.
Alternatively, the pop() method can also be used to remove a specific key and return its value.
del my_dictionary["profession"] # Removes a key and its value
removed_value = my_dictionary.pop("age") # Removes and returns the value of a key
Removing all elements from the dictionary
The clear() method is used to remove all elements from the dictionary, leaving it empty.
my_dictionary = {"name": "Luis", "age": 30, "city": "Madrid"}
my_dictionary.clear() # Removes all elements from the dictionary
print(my_dictionary) # Result: {}
