Dictionaries are unordered collections of key-value pairs, providing a way to associate values with unique keys.
Dictionaries are created by enclosing key-value pairs in curly braces {}
or by using the dict()
function. Each key-value pair is separated by a colon :
. Let's look at some examples:
# Creating dictionaries
student1 = {"name": "Alice", "age": 20, "major": "Computer Science"}
student2 = dict(name="Bob", age=21, major="Mathematics")
In the first example, we create a dictionary called student1
using curly braces and assigning values to keys. In the second example, we create a dictionary called student2
using the dict()
function and specifying key-value pairs using the key=value
syntax.
To access values in a dictionary, we use the corresponding keys:
# Accessing dictionary values
print(student1["name"]) # Output: Alice
print(student2["age"]) # Output: 21
In this example, we access and print the values associated with the keys "name"
and "age"
in the student1
and student2
dictionaries, respectively.
Python provides several methods and operations to work with dictionaries. Let's explore a few commonly used ones:
keys()
: Returns a view object containing the keys in the dictionary.
# Using the keys() method
print(student1.keys()) # Output: dict_keys(['name', 'age', 'major'])
values()
: Returns a view object containing the values in the dictionary.
# Using the values() method
print(student2.values()) # Output: dict_values(['Bob', 21, 'Mathematics'])
items()
: Returns a view object containing the key-value pairs in the dictionary.
# Using the items() method
print(student1.items()) # Output: dict_items([('name', 'Alice'), ('age', 20), ('major', 'Computer Science')])
get()
: Returns the value associated with a specified key. If the key is not found, it returns a default value (orNone
if not specified).
# Using the get() method
print(student2.get("major")) # Output: Mathematics
print(student1.get("gpa", 3.5)) # Output: 3.5 (default value)
These are just a few examples of the many methods and operations available for dictionaries in Python. Feel free to explore the Python documentation to discover more!
To iterate over a dictionary, we can use a for
loop combined with the items()
method. The items()
method returns a view object that contains the key-value pairs of the dictionary.
Let's see an example:
# Iterating over a dictionary
student = {"name": "Alice", "age": 20, "major": "Computer Science"}
for key, value in student.items():
print(key, ":", value)
In this example, we use a for
loop to iterate over the student
dictionary. The items()
method returns a view object containing the key-value pairs, which we unpack into the variables key
and value
. We then print each key-value pair.
The output will be:
name : Alice
age : 20
major : Computer Science
If you only need to iterate over the keys or values of a dictionary, you can use the keys()
or values()
methods, respectively. These methods return view objects that can be directly iterated over.
Let's see some examples:
# Iterating over keys
for key in student.keys():
print(key)
# Iterating over values
for value in student.values():
print(value)
In these examples, we use for
loops to iterate over the keys and values of the student
dictionary, respectively. The keys()
method returns a view object with the keys, while the values()
method returns a view object with the values.
Python also allows you to use comprehensions to create new dictionaries based on existing dictionaries while iterating over them. This can be done using dictionary comprehensions.
Let's see an example:
# Creating a new dictionary based on an existing dictionary
student = {"name": "Alice", "age": 20, "major": "Computer Science"}
new_student = {key: value for key, value in student.items() if key != "age"}
print(new_student)
In this example, we use a dictionary comprehension to create a new dictionary new_student
based on the student
dictionary. We iterate over the key-value pairs using items()
and conditionally include only those pairs where the key is not "age"
. The result is a new dictionary that excludes the "age"
key-value pair.
The output will be:
{'name': 'Alice', 'major': 'Computer Science'}