Python Dictionary
A dictionary stores data as key-value pairs. Dictionaries are useful when you need to access values using meaningful keys instead of numeric indexes.
Create a Dictionary
Python
Create a simple dictionary.
user = {
"name": "Alice",
"age": 25,
"city": "Bengaluru"
}
print(user)
Access Dictionary Values
Python
Access values using keys.
user = {"name": "Alice", "age": 25}
print(user["name"])
print(user.get("age"))
Add and Update Values
Python
Add a new key and update an existing value.
user = {"name": "Alice", "age": 25}
user["age"] = 26
user["email"] = "alice@example.com"
print(user)
Remove Values
Python
Remove dictionary entries.
user = {"name": "Alice", "age": 25, "city": "Bengaluru"}
del user["city"]
user.pop("age")
print(user)
Loop Through a Dictionary
Python
Loop through keys and values.
user = {"name": "Alice", "age": 25}
for key, value in user.items():
print(key, value)
Common Dictionary Methods
Useful methods include keys(), values(), items(), get(), update(), pop(), and clear().
Python
Using common dictionary methods.
user = {"name": "Alice", "age": 25}
print(user.keys())
print(user.values())
print(user.items())
Summary
Python dictionaries provide fast and convenient key-value storage. You can create, access, update, remove, and iterate over dictionary data using simple syntax.