What is a dictionary in Python
A dictionary in Python is a mutable data structure that is used to store a collection of key-value pairs. The keys in the dictionary are unique and immutable, and the values can be of any data type and can be duplicated.
Python dictionaries efficiently solve the tasks of fast data search, storage, and organization by using hash tables to provide O(1) element access time.
Creating a dictionary in Python
Empty dictionary
my_dict = {} # Empty dictionary
# or
my_dict = dict() # An alternative way to create an empty dictionary
Initializing a dictionary with data
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Creating a dictionary from a list of tuples
pairs = [('name', 'John'), ('age', 30), ('city', 'New York')]
my_dict = dict(pairs)
Creating a dictionary from a list of keys and values
keys = ['name', 'age', 'city']
values = ['John', 30, 'New York']
my_dict = dict(zip(keys, values))
Creating a dictionary using a generator
# Simple dictionary
generator my_dict = {x: x**2 for x in range(1, 6)}
# Generator with the condition
my_dict = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(my_dict) # Output: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
The fromkeys() method
keys = ['a', 'b', 'c']
default_value = 0
my_dict = dict.fromkeys(keys, default_value)
print(my_dict) # Output: {'a': 0, 'b': 0, 'c': 0}
Step-by-step addition of elements
my_dict = {}
my_dict['key1'] = 'value1'
my_dict['key2'] = 'value2'
my_dict['key3'] = 'value3'
print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Basic dictionary operations
Accessing dictionary elements
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
# Getting the value by key
print(my_dict['name']) # Outputs: John
# Safely getting the value using get()
print(my_dict.get('salary', 'Not specified')) # Outputs: Not specified
# Changing the value of the my_dict key
['age'] = 31
# Adding a new key-value pair
my_dict['gender'] = 'male'
# Deleting an element by key
del my_dict['city']
Key availability check
my_dict = {'name': 'John', 'age': 30}
# Checking for the key
if 'name' in my_dict:
print("The key 'name' exists")
# Checking for missing key
if 'salary' is not in my_dict:
print("The 'salary' key is missing")
Dictionary iteration
Key sorting
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
# Iterating over keys
for key in my_dict:
print(key)
# Explicit key enumeration
for key in my_dict.keys():
print(key)
Iterating through values
# Iterating over values
for value in my_dict.values():
print(value)
Iterating through key-value pairs
# Iterating key-value pairs
for key, value in my_dict.items():
print(f"{key}: {value}")
Nested dictionaries
Dictionaries can contain other dictionaries as values, which allows you to create complex data structures:
employees = {
'emp1': {'name': 'John', 'age': 30, 'department': 'IT'},
'emp2': {'name': 'Alice', 'age': 35, 'department': 'HR'}
}
# Access to embedded
print data(employees['emp1']['name']) # Outputs: John
# Changing embedded
employees data['emp1']['salary'] = 50000
# Adding a new employee
employees['emp3'] = {'name': 'Bob', 'age': 28, 'department': 'Marketing'}
Dictionary methods in Python
Basic dictionary methods
method| The | Description |
|---|---|
keys() |
Returns a representation of all dictionary keys |
values() |
Returns a representation of all dictionary values |
items() |
Returns a representation of key-value pairs |
get(key, default) |
Returns the value by key or default |
pop(key, default) |
Deletes and returns the key value |
popitem() |
Deletes and returns an arbitrary pair |
update(other_dict) |
Updates the dictionary with data from another dictionary |
clear() |
Deletes all dictionary elements |
copy() |
Creates a surface copy of the dictionary |
setdefault(key, default) |
Returns the value or sets the default |
fromkeys(keys, value) |
Creates a dictionary of keys with the same value |
Examples of using methods
clear() - Clearing the dictionary
my_dict = {'a': 1, 'b': 2}
my_dict.clear()
print(my_dict) # Output: {}
copy() - Create a copy
original_dict = {'a': 1, 'b': 2}
copied_dict = original_dict.copy()
print(copied_dict) # Output: {'a': 1, 'b': 2}
get() - Getting the value safely
my_dict = {'a': 1, 'b': 2}
value = my_dict.get('a')
print(value) # Output: 1
# With default value
value = my_dict.get('c', 'Not found')
print(value) # Output: Not found
pop() - Delete with return value
my_dict = {'a': 1, 'b': 2}
value = my_dict.pop('a')
print(value) # Output: 1
print(my_dict) # Output: {'b': 2}
popitem() - Deleting an arbitrary pair
my_dict = {'a': 1, 'b': 2}
item = my_dict.popitem()
print(item) # Output: ('b', 2)
print(my_dict) # Output: {'a': 1}
setdefault() - Setting the default value
my_dict = {'a': 1, 'b': 2}
value = my_dict.setdefault('c', 3)
print(value) # Output: 3
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
update() - Dictionary update
my_dict = {'a': 1, 'b': 2}
my_dict.update({'c': 3, 'd': 4})
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Updating with a different dictionary
other_dict = {'e': 5, 'f': 6}
my_dict.update(other_dict)
Practical examples of using dictionaries
Counting elements
text = "hello world"
char_count = {}
for char in text:
char_count[char] = char_count.get(char, 0) + 1
print(char_count) # {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Data grouping
students = [
{'name': 'John', 'grade': 'A'},
{'name': 'Alice', 'grade': 'B'},
{'name': 'Bob', 'grade': 'A'},
{'name': 'Charlie', 'grade': 'C'}
]
grades = {}
for student in students:
grade = student['grade']
if grade not in grades:
grades[grade] = []
grades[grade].append(student['name'])
print(grades) # {'A': ['John', 'Bob'], 'B': ['Alice'], 'C': ['Charlie']}
Caching of results
cache = {}
def expensive_function(n):
if n in cache:
return cache[n]
result = n ** 2 # Simulation of complex calculations
cache[n] = result
return result
Features and limitations of dictionaries
Key requirements
Dictionary keys must be immutable data types:
- Strings, numbers, tuples - you can use
- Lists, dictionaries, sets - cannot be used
# Correct
valid_dict = {
'string_key': 'value',
42: 'numeric_key',
(1, 2): 'tuple_key'
}
# Incorrect - will cause an error
# invalid_dict = {[1, 2]: 'list_key'} # TypeError
Performance
Dictionaries provide fast access to elements with an average complexity of O(1) for search, insertion, and deletion operations.
The order of the elements
Starting with Python 3.7, dictionaries preserve the insertion order of elements, which makes them more predictable to use.
Python dictionaries are a powerful tool for working with data and are widely used in various programming tasks due to their efficiency and flexibility.