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.
Creation of a dictionary
Section titled “Creation of a dictionary”A dictionary is defined with key:value pairs enclosed in curly braces {}
.
# Definition of a dictionaryperson = {'name': 'Ana','age': 28,'city': 'Bogotá'}
# Show complete dictionaryprint(person)
Output:
{'name': 'Ana', 'age': 29, 'city': 'Bogotá'}
Indexing
Section titled “Indexing”Allows accessing a value from a dictionary using its key as an index.
# Definition of a dictionaryperson = {'name': 'Ana','age': 28,'city': 'Bogotá'}
# Access valuesprint(person['name']) # Anaprint(person['age']) # 28
Output:
Ana28
Accessing values
Section titled “Accessing values”Print the dictionary to see all current key:value pairs.
# Definition of a dictionaryperson = {'name': 'Ana','age': 28,'city': 'Bogotá'}
# Show complete dictionaryprint(person)
Output:
{'name': 'Ana', 'age': 28, 'city': 'Bogotá'}
Adding a key:value pair
Section titled “Adding a key:value pair”You can add new data by assigning a value to a new key.
# Definition of a dictionaryperson = {'name': 'Ana','age': 28,'city': 'Bogotá'}
# Add a new key:value pairperson['profession'] = 'Engineer'
# Show complete dictionaryprint(person)
Output:
{'name': 'Ana', 'age': 28, 'city': 'Bogotá', 'profession': 'Engineer'}
Modifying an existing value
Section titled “Modifying an existing value”You can update the value of an existing key by assigning a new value.
# Definition of a dictionaryperson = {'name': 'Ana','age': 28,'city': 'Bogotá'}
# Modify an existing valueperson['age'] = 29
# Show complete dictionaryprint(person)
Output:
{'name': 'Ana', 'age': 29, 'city': 'Bogotá'}
Deleting a key
Section titled “Deleting a key”Use del
to delete a key along with its value from the dictionary.
# Definition of a dictionaryperson = {'name': 'Ana','age': 28,'city': 'Bogotá'}
# Delete a keydel person['city']
# Show complete dictionaryprint(person)
Output:
{'name': 'Ana', 'age': 28}