A Data Structure Comprising Keys and Values: Dictionary
In programming, you may encounter situations where you need to store a pairing of a person's name with their age or manage a product name alongside its price.
In cases where you need to manage data in pairs of key
and value
, Python uses a data structure called Dictionary
.
What is a Dictionary?
In a Dictionary, the key serves as an identifier (ID)
for the data and the value represents the content
of that data.
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
In the code above, "key1"
, "key2"
, and "key3"
are keys, and "value1"
, "value2"
, and "value3"
are the corresponding values.
A pair consisting of a key and its value, like key1 and value1, is known as an item
. It is also referred to as an element
or entry
.
Creating a Dictionary
A dictionary is created using curly brackets { }
. Keys and values are separated by a colon (:)
, and multiple key-value pairs are separated by commas (,)
.
# Dictionary to store a student's name, age, and major
student = {
"name": "Alex",
"age": 22,
"major": "Computer Science"
}
In this code, "name"
, "age"
, and "major"
are keys, and "Alex"
, 22
, and "Computer Science"
are the corresponding values.
Accessing Keys and Values in a Dictionary
The biggest advantage of a dictionary is that, no matter how much data it contains, you can quickly access values using their corresponding keys.
It's similar to how knowing a zip code (key) allows you to quickly find an address (value).
Accessing Values Using Keys
To retrieve the value corresponding to a specific key in a dictionary, you input the key as a string within square brackets [ ]
.
student = {
"name": "Alex",
"age": 22,
"major": "Computer Science"
}
# Output: Alex
print(student["name"])
# Output: Computer Science
print(student["major"])
If you request a value using a key that doesn't exist within the dictionary, Python raises a KeyError
.
student = {
"name": "Alex",
"age": 22,
"major": "Computer Science"
}
# KeyError raised
print(student["address"])
Checking the Existence of a Key
To determine if a specific key exists in a dictionary, use the in
keyword.
student = {
"name": "Alex",
"age": 22,
"major": "Computer Science"
}
# Check if key exists using the in keyword
if "age" in student:
print("Age is:", student["age"])
else:
print("Key not found")
In the code above, it checks whether the key "age"
exists in the dictionary. If the key exists, it prints the value of age
. If the key doesn't exist, it prints "Key not found".
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.