Language: EN


Dictionaries in Python

A dictionary is an unordered collection of key-value pairs. The keys are unique and immutable, while the values can be of any type and can be modified.

Characteristics of dictionaries:

  • Unique keys: Each key in a dictionary is unique, which means that there cannot be duplicate keys.
  • Value mutability: The values of a dictionary can be modified after creation.
  • Unordered: Although dictionaries maintain the insertion order from Python 3.7 onwards, the order should not be relied upon as it can vary in different versions.

Creating a dictionary

Dictionaries are defined using braces {} and key-value pairs are separated by colons :.

To create a dictionary in Python, the following syntax is used:

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.

Or for example like this.

my_dictionary = {"name": "John", "age": 30, "profession": "Engineer"}

In this example, my_dictionary is a dictionary with three key-value pairs: “name” with the value “John”, “age” with the value 30, and “profession” with the value “Engineer”.

Operations with Dictionaries

Accessing elements

To access the values of a dictionary, the corresponding key is used as follows:

print(my_dictionary["name"])  # Result: John
print(my_dictionary["age"])  # Result: 30

Modifying elements

To modify a dictionary, 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, the syntax my_dictionary["new_key"] = new_value can be used.

my_dictionary["city"] = "Madrid"  # Add a new key-value pair

Keep in mind that if the key already exists in the dictionary, the associated value will be overwritten with the new provided value, as we have seen in the previous section.

Verifying key membership

To check if a key is present in a dictionary, the in expression can be used. 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 key-value pairs of the dictionary as tuples.

my_dictionary = {"name": "John", "age": 30, "city": "Madrid"}
items_view = my_dictionary.items()  # Returns a view of the key-value pairs
print(items_view)  # Result: dict_items([('name', 'John'), ('age', 30), ('city', 'Madrid')])

On the other hand, we also have the keys() method that returns a list of all the keys in the dictionary, and the values() method that 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 that a new dictionary instance is created containing the same key-value pairs as the original dictionary.

my_dictionary = {"name": "John", "age": 30, "city": "Madrid"}
copy_dictionary = my_dictionary.copy()  # Creates a shallow copy of the dictionary

print(copy_dictionary)  # Result: {"name": "John", "age": 30, "city": "Madrid"}

Note that the copy is shallow. If the dictionary values are references, the values of the copy will point to the same objects.

Deleting elements

There are several ways to delete elements from a dictionary in Python. The del statement can be used followed by the name of the key to delete the key and its corresponding value.

Alternatively, the pop() method can also be used to delete a specific key and return its value.

del my_dictionary["profession"]  # Deletes a key and its value
deleted_value = my_dictionary.pop("age")  # Deletes and returns the value of a key

Deleting all elements of the dictionary

The clear() method is used to delete all elements of the dictionary, leaving it empty.

my_dictionary = {"name": "John", "age": 30, "city": "Madrid"}
my_dictionary.clear()  # Deletes all elements of the dictionary
print(my_dictionary)  # Result: {}