Junior — Middle
Explain what a dictionary in Python is and how it works.
sobes.tech AI
Answer from AI
In Python, a dictionary (dict) is a mutable data structure that stores key-value pairs. It is implemented as a hash table, which provides fast access to values by key.
Main features of a dictionary:
- Keys must be hashable (e.g., strings, numbers, tuples with hashable elements).
- Fast access to values by key — insertion, deletion, and search operations have an amortized complexity of O(1).
- Order of elements is preserved starting from Python 3.7 (officially guaranteed).
Example of using a dictionary:
# Creating a dictionary
person = {'name': 'Ivan', 'age': 30}
# Adding an element
person['city'] = 'Moscow'
# Getting a value by key
print(person['name']) # Ivan
# Checking if a key exists
if 'age' in person:
print('Age:', person['age'])
# Iterating over keys and values
for key, value in person.items():
print(f'{key}: {value}')
Thus, a dictionary is a convenient and efficient way to store and access related data by key.