Skip to content

Dictionaries

In Python, dictionaries are data structures that store key-value pairs. Keys must be unique and immutable (such as strings, numbers, or tuples), while values can be of any type. Dictionaries are used to store and retrieve information efficiently, where a key serves to identify the associated value.

A dictionary is defined with key:value pairs enclosed in curly braces {}.

dictionary.py
# Definition of a dictionary
person = {
'name': 'Ana',
'age': 28,
'city': 'Bogotá'
}
# Show complete dictionary
print(person)

Output:

dictionary.py
{'name': 'Ana', 'age': 29, 'city': 'Bogotá'}

Allows accessing a value from a dictionary using its key as an index.

dictionary.py
# Definition of a dictionary
person = {
'name': 'Ana',
'age': 28,
'city': 'Bogotá'
}
# Access values
print(person['name']) # Ana
print(person['age']) # 28

Output:

dictionary.py
Ana
28

Print the dictionary to see all current key:value pairs.

dictionary.py
# Definition of a dictionary
person = {
'name': 'Ana',
'age': 28,
'city': 'Bogotá'
}
# Show complete dictionary
print(person)

Output:

dictionary.py
{'name': 'Ana', 'age': 28, 'city': 'Bogotá'}

You can add new data by assigning a value to a new key.

dictionary.py
# Definition of a dictionary
person = {
'name': 'Ana',
'age': 28,
'city': 'Bogotá'
}
# Add a new key:value pair
person['profession'] = 'Engineer'
# Show complete dictionary
print(person)

Output:

dictionary.py
{'name': 'Ana', 'age': 28, 'city': 'Bogotá', 'profession': 'Engineer'}

You can update the value of an existing key by assigning a new value.

dictionary.py
# Definition of a dictionary
person = {
'name': 'Ana',
'age': 28,
'city': 'Bogotá'
}
# Modify an existing value
person['age'] = 29
# Show complete dictionary
print(person)

Output:

dictionary.py
{'name': 'Ana', 'age': 29, 'city': 'Bogotá'}

Use del to delete a key along with its value from the dictionary.

dictionary.py
# Definition of a dictionary
person = {
'name': 'Ana',
'age': 28,
'city': 'Bogotá'
}
# Delete a key
del person['city']
# Show complete dictionary
print(person)

Output:

dictionary.py
{'name': 'Ana', 'age': 28}