Language: EN

python-diccionarios

Dictionaries in Python

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
  • Mutability of values: The values of a dictionary can be modified after creation
  • Unordered: Although dictionaries maintain insertion order starting from Python 3.7, one should not rely on the order

Creating a dictionary

Dictionaries in Python are defined using curly braces {} and key-value pairs are separated by colons :. 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”

  • age with the value 30
  • 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: Luis
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, 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 value provided (as we have seen in the previous section).

Checking key membership

To check if a key is present in a dictionary, you can use the expression in. 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 method items() returns a view of the key-value pairs of the dictionary 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 dictionary

  • values() which 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 method copy() returns a shallow copy of the dictionary. This means that a new dictionary instance is created that contains 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"}

Note that the copy is shallow. If the values of the dictionary 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 remove 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: {}