Dictionaries in Python are used to store data in key–value pairs. They are unordered, changeable, and indexed by keys, making them ideal for structured data.
Dictionaries are written using curly braces {}.
Why Dictionaries Are Important
Dictionaries help to:
- Store structured data
- Access values quickly using keys
- Represent real-world data
- Build efficient applications
Example:
student = {
"name": "Aman",
"age": 21,
"course": "Python"
}
Creating a Dictionary in Python
person = {"name": "Ravi", "city": "Delhi"}
Accessing Dictionary Values
print(person["name"])
print(person.get("city"))
Modifying Dictionary Values
person["city"] = "Mumbai"
Adding New Key-Value Pairs
person["country"] = "India"
Removing Dictionary Items
person.pop("city")
del person["name"]
Looping Through a Dictionary
for key, value in person.items():
print(key, value)
Common Dictionary Methods
| Method | Description |
|---|---|
| keys() | Returns keys |
| values() | Returns values |
| items() | Returns key-value pairs |
| update() | Updates dictionary |
Nested Dictionaries
students = {
"student1": {"name": "Aman", "age": 20},
"student2": {"name": "Neha", "age": 22}
}
Conclusion
Dictionaries are essential for storing and managing structured data efficiently. They are widely used in real-world Python applications.
References
- Internal Reference: https://savanka.com/category/learn/python/
- External Reference: https://www.w3schools.com/python/