Dictionaries in Python: Creating and Working with Keys
Dictionaries in Python are one of the most powerful and convenient data structures. They allow you to store information in a "key-value" format. Due to their flexibility and high speed of data access, dictionaries are actively used when working with JSON files. They are also indispensable when working with databases and processing configurations. Dictionaries are used in many other areas of programming.
In this guide, we will take a detailed look at creating dictionaries in Python. We will learn how to work with their keys and values. We will also analyze popular methods and best practices for use.
What is a Dictionary in Python?
A dictionary is a collection that stores key-value pairs. Keys must be unique and immutable. Numbers, strings, or tuples can be used as keys. Values can be any Python objects.
Key characteristics of dictionaries:
- Unordered collection of data (before Python 3.7)
- Mutable data structure
- Fast access to elements by key
- Automatic hashing of keys
person = {
"name": "Иван",
"age": 30,
"city": "Москва"
}
Features of Keys in Dictionaries
Dictionary keys must meet certain requirements:
- Be immutable data types
- Be unique within one dictionary
- Support hashing
How to Create a Dictionary in Python
Using Curly Braces
The most common way to create a dictionary is to use curly braces. This method is intuitive and often used by developers.
car = {"brand": "Toyota", "year": 2020, "color": "white"}
Creating with the dict() Function
The dict() function provides an alternative way to create dictionaries. This approach is especially useful when creating dictionaries from other data structures.
car = dict(brand="Toyota", year=2020, color="white")
Creating an Empty Dictionary
Empty dictionaries are created for subsequent data filling. This is useful when initializing data structures.
empty_dict = {}
# or
empty_dict = dict()
Creating a Dictionary from Sequences
Dictionaries can be created from lists of tuples or other sequences:
pairs = [("name", "Анна"), ("age", 25), ("city", "Санкт-Петербург")]
person_dict = dict(pairs)
Working with Keys in a Dictionary
Accessing a Value by Key
To get a value by key, the syntax of square brackets is used. When accessing a non-existent key, a KeyError exception occurs.
person = {"name": "Иван", "age": 30}
print(person["name"]) # Output: Иван
Safe Access with the get() Method
The get() method provides a safe way to get values. If the key is missing, a default value is returned instead of an exception.
print(person.get("city", "Город не указан")) # Output: Город не указан
print(person.get("name")) # Output: Иван
Adding and Changing Values
Dictionaries support dynamic addition of new elements. When assigning a value to an existing key, the data is updated.
person["city"] = "Москва" # Add a new key
person["age"] = 31 # Change an existing value
Removing Keys from a Dictionary
There are several ways to remove elements from a dictionary:
del person["age"] # Removes the 'age' key and its value
removed_value = person.pop("city", "Не найдено") # Removes and returns the value
person.popitem() # Removes an arbitrary key-value pair
Iterating Through Keys and Values
Dictionaries support various ways to iterate through elements:
# Iterating through keys and values
for key, value in person.items():
print(f"{key}: {value}")
# Iterating through keys only
for key in person.keys():
print(key)
# Iterating through values only
for value in person.values():
print(value)
Adding Values to a Python Dictionary
Direct Assignment
When adding a new element to a Python dictionary, a new key-value pair is automatically created. If the key already exists, its value is updated.
data = {}
data["username"] = "admin"
data["password"] = "12345"
data["role"] = "administrator"
print(data) # {'username': 'admin', 'password': '12345', 'role': 'administrator'}
Using the update() Method
The update() method allows you to add multiple elements at the same time. This method is effective when working with large amounts of data.
data.update({"email": "admin@example.com", "active": True})
Getting a Dictionary Value in Python
Direct Access via Key
Direct access to a dictionary element via a key is the fastest way to get data:
value = data["username"] # 'admin'
Using the get() Method
The get() method provides a safer way to get values with the ability to specify a default value:
value = data.get("email", "Email не задан") # Returns a value or a default value
phone = data.get("phone") # Returns None if the key is missing
Popular Methods for Working with Dictionaries
Basic Methods
dict.keys()- returns a view of all dictionary keysdict.values()- returns a view of all valuesdict.items()- returns a view of key-value pairsdict.get(key, default)- safely gets a value by keydict.update(other)- updates the dictionary with elements from another dictionarydict.pop(key, default)- removes an element by key and returns its value
Additional Methods
dict.setdefault(key, default)- returns the value of a key or sets a default valuedict.clear()- clears the entire dictionarydict.copy()- creates a shallow copy of the dictionarydict.popitem()- removes and returns an arbitrary key-value pair
# Examples of using methods
person = {"name": "Анна", "age": 25}
# Getting all keys
keys = list(person.keys()) # ['name', 'age']
# Creating a copy of the dictionary
person_copy = person.copy()
# Setting a default value
person.setdefault("city", "Неизвестно")
Practical Examples of Using Dictionaries
Counting the Number of Words in Text
Dictionaries are great for counting the frequency of elements. This pattern is often used in data analysis.
text = "python python code dict python dict programming"
words = text.split()
counter = {}
for word in words:
counter[word] = counter.get(word, 0) + 1
print(counter) # {'python': 3, 'code': 1, 'dict': 2, 'programming': 1}
Replacing a Switch-Case Construct
Python does not have a switch-case operator, but dictionaries can effectively replace it:
def get_monday():
return "Понедельник"
def get_tuesday():
return "Вторник"
def get_wednesday():
return "Среда"
days = {
1: get_monday,
2: get_tuesday,
3: get_wednesday
}
print(days[1]()) # Output: Понедельник
Grouping Data
Dictionaries are convenient for grouping data according to certain criteria:
students = [
{"name": "Анна", "group": "A"},
{"name": "Петр", "group": "B"},
{"name": "Мария", "group": "A"}
]
grouped = {}
for student in students:
group = student["group"]
if group not in grouped:
grouped[group] = []
grouped[group].append(student["name"])
print(grouped) # {'A': ['Анна', 'Мария'], 'B': ['Петр']}
Frequently Asked Questions
Can Lists be Used as Dictionary Keys?
No, lists cannot be used as dictionary keys. Keys must be immutable data types. You can use strings, numbers, tuples, or other hashable objects.
# Incorrect
# my_dict = {[1, 2]: "value"} # Will cause TypeError
# Correct
my_dict = {(1, 2): "value"} # A tuple can be used as a key
Combining Two Dictionaries
There are several ways to combine dictionaries in Python:
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
# Method 1: unpacking (Python 3.5+)
merged = {**dict1, **dict2}
# Method 2: update() method
dict1.update(dict2)
# Method 3: operator | (Python 3.9+)
merged = dict1 | dict2
print(merged) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Checking for the Presence of a Key in a Dictionary
To check for the existence of a key in a dictionary, the in operator is used:
person = {"name": "Анна", "age": 25}
if "name" in person:
print("Ключ существует")
if "email" not in person:
print("Ключ отсутствует")
Overwriting an Existing Key
When adding a key that already exists in the dictionary, its value is overwritten:
data = {"key": "old_value"}
data["key"] = "new_value"
print(data) # {"key": "new_value"}
Creating a Nested Dictionary
Dictionaries can contain other dictionaries as values. This allows you to create complex hierarchical data structures:
student = {
"name": "Анна",
"grades": {
"math": 5,
"english": 4,
"physics": 5
},
"contact": {
"email": "anna@example.com",
"phone": "+7-123-456-7890"
}
}
# Accessing nested data
math_grade = student["grades"]["math"] # 5
Clearing a Dictionary
To remove all elements from a dictionary, the clear() method is used:
data = {"key1": "value1", "key2": "value2"}
data.clear()
print(data) # {}
Optimizing Work with Dictionaries
Using defaultdict
The collections module provides defaultdict - a dictionary with default values:
from collections import defaultdict
# Automatically creates a list for new keys
grouped = defaultdict(list)
for item in ["a", "b", "a", "c", "b"]:
grouped[item].append(1)
Sorting Dictionaries
Dictionaries can be sorted by keys or values:
data = {"c": 3, "a": 1, "b": 2}
# Sorting by keys
sorted_by_keys = dict(sorted(data.items()))
# Sorting by values
sorted_by_values = dict(sorted(data.items(), key=lambda x: x[1]))
Conclusion
Dictionaries are a versatile tool for storing and processing structured data in Python. They provide fast access to information through unique keys. The ability to work effectively with keys and values allows you to write cleaner and more understandable code.
Correct use of dictionary methods improves application performance. Knowledge of various ways to create and modify dictionaries expands the capabilities of the developer. Applying the approaches discussed in the guide will help you confidently operate with dictionaries in Python projects.
The Future of AI in Mathematics and Everyday Life: How Intelligent Agents Are Already Changing the Game
Experts warned about the risks of fake charity with AI
In Russia, universal AI-agent for robots and industrial processes was developed