This is my favorite data structure in Python and I hope I can sell you on the greatness of dictionaries. If you love organization, structure, and blazing fast performance, you will love dictionaries as well.
Python dictionaries are versatile and efficient data structures that allow you to store and access data using key-value pairs. In this tutorial, we'll cover the basics of dictionaries, how to create and manipulate them, and some common use cases.
What is a Dictionary?
A dictionary is an unordered collection of key-value pairs. Each key is unique and maps to a specific value. Dictionaries are mutable, which means you can add, remove, or modify elements after the dictionary has been created.
Creating a Dictionary
You can create a dictionary using the curly braces {}
and separating keys and values with colons. To define an empty dictionary, use {}
or dict()
.
# Creating an empty dictionary
empty_dict = {}
empty_dict2 = dict()
# Creating a dictionary with key-value pairs
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
Accessing Dictionary Elements
To access the value associated with a specific key, use the square bracket notation []
. If the key doesn't exist, a KeyError
will be raised. You can also use the get()
method to avoid this error and return a default value if the key is not found.
# Accessing values using keys
print(person["name"]) # Output: Alice
# Using the get() method
print(person.get("country", "USA")) # Output: USA
Adding or Updating Elements
You can add a new key-value pair or update an existing one using the assignment operator =
.
# Adding a new key-value pair
person["job"] = "Software Engineer"
# Updating an existing key-value pair
person["age"] = 31
Removing Elements
To remove a key-value pair, use the del
keyword followed by the key. If the key doesn't exist, a KeyError
will be raised.
# Removing a key-value pair
del person["city"]
Dictionary Methods
Python dictionaries come with several built-in methods that make it easy to work with them.
keys()
: Returns a view object displaying a list of all the keys.values()
: Returns a view object displaying a list of all the values.items()
: Returns a view object displaying a list of all the key-value pairs as tuples.update()
: Merges two dictionaries, adding or updating key-value pairs from the second dictionary into the first.clear()
: Removes all items from the dictionary.
# Using dictionary methods
print(person.keys()) # Output: dict_keys(['name', 'age', 'job'])
print(person.values()) # Output: dict_values(['Alice', 31, 'Software Engineer'])
print(person.items()) # Output: dict_items([('name', 'Alice'), ('age', 31), ('job', 'Software Engineer')])
person.update({"city": "San Francisco", "country": "USA"})
print(person) # Output: {'name': 'Alice', 'age': 31, 'job': 'Software Engineer', 'city': 'San Francisco', 'country': 'USA'}
person.clear()
print(person) # Output: {}
Looping Through a Dictionary
You can loop through a dictionary's keys, values, or key-value pairs using a for loop and the appropriate dictionary method.
# Looping through keys
for key in person.keys():
print(key)
# Looping through values
for value in person.values():
print(value)
# Looping through key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Dictionary Comprehensions
Similar to list comprehensions, you can use dictionary comprehensions to create dictionaries in a concise and readable way.
# Using a dictionary comprehension to create a dictionary
squares = {num: num ** 2 for num in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Nested Dictionaries
Dictionaries can be nested inside other dictionaries, allowing you to create more complex data structures.
# Creating a nested dictionary
employees = {
"employee1": {
"name": "Alice",
"age": 30,
"job": "Software Engineer"
},
"employee2": {
"name": "Bob",
"age": 35,
"job": "Data Analyst"
}
}
# Accessing values in a nested dictionary
print(employees["employee1"]["name"]) # Output: Alice