Python Dictionaries
Python dictionaries are data structures that store key-value pairs. They are also known as associative arrays or hash maps in other programming languages. Dictionaries are unordered, mutable, and iterable objects in Python.
Here’s an example of a dictionary in Python:
python
student = {
"name": "John Smith",
"age": 20,
"university": "ABC University",
"major": "Computer Science"
}
In this example, "name"
, "age"
, "university"
, and "major"
are keys, and "John Smith"
, 20
, "ABC University"
, and "Computer Science"
are their corresponding values.
You can access the values in a dictionary by using the keys:
python
print(student["name"]) # Output: John Smith
print(student["age"]) # Output: 20
You can also modify the values or add new key-value pairs to a dictionary:
python
student["age"] = 21 # Modifying the value
student["email"] = "[email protected]" # Adding a new key-value pair
print(student["age"]) # Output: 21
print(student["email"]) # Output: [email protected]
To check if a key exists in a dictionary, you can use the in
operator:
python
if "major" in student:
print("Major:", student["major"])
else:
print("Major not found")
You can iterate over the keys, values, or items (both keys and values) of a dictionary using loops:
python
# Iterating over keys
for key in student:
print(key)
# Iterating over values
for value in student.values():
print(value)
# Iterating over items
for key, value in student.items():
print(key, ":", value)
Dictionaries are commonly used when you want to store and retrieve data using a meaningful key instead of numeric indices. They provide a flexible and efficient way to organize and access data.