1.1 Dictionary and its properties
A dictionary in Python is an ordered collection of key-value pairs, where each key is unique. Dictionaries are one of the most flexible and powerful data types in Python, used for storing and managing data. We will use them very often, almost as frequently as lists. You will see for yourself soon enough :)
Main properties of dictionaries:
1. Unique Keys
Each key in a dictionary must be unique. If a key-value pair is added to the dictionary with a key that already exists, the old value will be replaced with the new one. For example, if you want to store data about students and use their IDs as keys:
students = {"123": "John", "124": "Alice", "123": "Mike"}
print(students) # Output: {'123': 'Mike', '124': 'Alice'}
2. Ordered
Important! Prior to Python 3.7, dictionaries were unordered collections, meaning the order of elements was not guaranteed. Starting with Python 3.7, dictionaries maintain insertion order, but this aspect is not an official part of the language specification until Python 3.8, where it became standard.
That was 5 years ago. We're studying Python based on version 3.12, so you can confidently consider a dictionary an ordered set of items.
3. Mutability
Dictionaries are mutable, meaning you can add, change, or remove elements after the dictionary has been created. For example, let's add a student's address:
student = {"name": "John", "age": 20}
student["address"] = "123 Main St"
print(student) # Output: {'name': 'John', 'age': 20, 'address': '123 Main St'}
4. Efficiency
Dictionaries are optimized for fast lookups, additions, and deletions of key-value pairs. On average, search, addition, and deletion operations are performed in constant time, O(1). What algorithm complexity is, you'll learn a bit later, when we study the topics "Algorithms and Data Structures."
5. Keys and Values
Dictionary keys can be any immutable data type, such as strings, numbers, or tuples. Values can be any data type, including other dictionaries.
6. Access and modification methods
Dictionaries support various methods for accessing elements, adding, changing, and removing key-value pairs. Some of these methods include get(), keys(), values(), items(), update(), pop(), and others. More details in subsequent lectures.
7. Iterating over elements
You can iterate over keys, values, or key-value pairs in a dictionary using loops. This makes it easy to perform operations on dictionary elements. For example:
student = {"name": "John", "age": 20, "address": "123 Main St"}
for key, value in student.items():
print(f"{key}: {value}")
Output will be:
name: John
age: 20
address: 123 Main St
8. Hashability of keys
Keys in a dictionary must be hashable (from the word hash). This means that keys must have a hash value that does not change throughout their lifetime. A hash value is obtained using a hash function, an algorithm that converts input data of arbitrary length into a fixed-length output value. This is called a hash value or hash code. Immutable data types, such as strings, numbers, and tuples, are hashable and can be used as keys.
We'll delve deeper into hash functions and hashability in the "Algorithms and Data Structures" topic.
1.2 Creating a dictionary using {}
Dictionaries in Python can be created in several ways. Here are various ways to create a dictionary object with examples:
Using curly braces {}
The most common way to create a dictionary is to use curly braces with key-value pairs separated by commas. The key-value pair itself is separated by a colon.
# Create an empty dictionary
empty_dict = {}
# Create a dictionary with elements
person = {
"name": "John",
"age": 30,
"city": "New York"
}
print(type(person))
print(person)
Important! Creating a dictionary is similar to creating a set. You can even consider a dictionary as a set of keys with associated values.
If the curly braces simply list "keys," a set is created; if keys are followed by a colon and values are specified, a dictionary is created. Empty curly braces always create a dictionary.
# Create an empty dictionary
empty_dict = {}
# Create a set with elements
unique_items = {
"name",
"age",
"city"
}
print(type(unique_items))
print(unique_items)
1.3 Creating a dictionary using the dict() function
The dict() function can be used to create a dictionary from a sequence of key-value pairs, as well as from named arguments.
Example with a sequence of key-value pairs:
# Create a dictionary from a list of tuples
person = dict([("name", "John"), ("age", 30), ("city", "New York")])
print(person)
Example with named arguments. No additional brackets needed here:
# Create a dictionary with named arguments
person = dict(name="John", age=30, city="New York")
print(person)
Using the dict.fromkeys() method
The fromkeys() method creates a dictionary with specified keys and a default value.
# Create a dictionary with keys and a default value
keys = ["name", "age", "city"]
default_value = None
person = dict.fromkeys(keys, default_value)
print(person)
The dictionary will have three keys, but they will all contain the same value.
1.4 Creating a dictionary from existing variables
Dictionaries can be created using variables as keys and values.
# Create a dictionary from variables
name = "John"
age = 30
city = "New York"
person = {"name": name, "age": age, "city": city}
print(person)
1.5 Using dictionary comprehensions
Dictionary comprehensions allow you to create dictionaries using concise and clear constructs, similar to list comprehensions.
# Create a dictionary using dictionary comprehension
squares = {x: x**2 for x in range(1, 6)}
print(squares)
1.6 Accessing values in a dictionary
To get a value by key, use the [] syntax:
# Accessing values in a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
print(person["name"]) # Output: John
Important! If the key is not found, a KeyError will occur. To avoid this, you can use the get() method, which returns the value for a key if it exists, or None (or another default value) if the key is not found.
# Using the get() method to access values in a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
print(person.get("name")) # Output: John
print(person.get("address", "Address not found")) # Output: Address not found
1.7 Modifying values in a dictionary
You can modify values in a dictionary by accessing them by key and assigning a new value.
# Modifying values in a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
person["age"] = 31
print(person) # Output: {'name': 'John', 'age': 31, 'city': 'New York'}
1.8 Removing elements from a dictionary
You can remove elements using the del operator or the pop() method.
# Remove an element using del
person = {"name": "John", "age": 30, "city": "New York"}
del person["age"]
print(person) # Output: {'name': 'John', 'city': 'New York'}
# Remove an element using pop()
person = {"name": "John", "age": 30, "city": "New York"}
age = person.pop("age")
print(person) # Output: {'name': 'John', 'city': 'New York'}
print(age) # Output: 30
1.9 Checking the presence of a key in a dictionary
You can check if a key is in a dictionary using the in operator.
# Check for the presence of a key in a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
print("name" in person) # Output: True
print("address" in person) # Output: False
1.10 Iterating over dictionary elements
You can iterate over keys, values, or key-value pairs in a dictionary:
# Iterate over dictionary keys
person = {"name": "John", "age": 30, "city": "New York"}
for key in person:
print(key)
# Iterate over dictionary values
for value in person.values():
print(value)
# Iterate over dictionary key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
1.11 Examples of dictionary usage in real-world tasks
Let's look at some real-life examples where the use of dictionaries might be helpful:
Example 1: Counting word frequency in text
Let's say we have a text and we want to count how many times each word occurs in the text.
text = "hello world hello"
word_count = {}
for word in text.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count) # Output: {'hello': 2, 'world': 1}
Example 2: Storing student data
We can use a dictionary to store student data, where the keys will be their IDs and the values will be their data.
students = {
"123": {"name": "John", "age": 20, "major": "Computer Science"},
"124": {"name": "Alice", "age": 22, "major": "Mathematics"}
}
print(students["123"]["name"]) # Output: John
Example 3: Phone book
Dictionaries can be used to create a simple phone book, where the keys are names and the values are phone numbers.
phone_book = {
"John": "123-456-7890",
"Alice": "987-654-3210"
}
print(phone_book["Alice"]) # Output: 987-654-3210
GO TO FULL VERSION