Dictionaries use curly braces {}
and consist of key–value pairs:
my_dict = {"name": "Ali", "age": 25, "is_active": True}
empty_dict = {}
mixed_keys = {1: "one", True: "yes", 3.14: "pi"}
person = {"name": "Zara", "city": "Doha"}
print(person["name"]) # 'Zara'
person["age"] = 30 # Adds new key
person["city"] = "Dubai" # Modifies value
Method | Description |
---|---|
get(key, default) | Returns value of key or default |
keys() | Returns all keys |
values() | Returns all values |
items() | Returns all key–value pairs |
update(dict2) | Merges another dictionary |
pop(key) | Removes key and returns value |
popitem() | Removes and returns last item |
clear() | Empties the dictionary |
copy() | Returns a shallow copy |
user = {"username": "shahin", "role": "admin"}
print(user.get("email", "not found")) # 'not found'
print(user.keys()) # dict_keys(['username', 'role'])
print(user.values()) # dict_values(['shahin', 'admin'])
user.update({"email": "[email protected]"})
print(user.pop("role")) # 'admin'
print(user) # {'username': 'shahin', 'email': '[email protected]'}
data = {
"user": {"name": "Ali", "age": 27},
"status": {"online": True, "verified": False}
}
for section, info in data.items():
print(section, info)
Dictionaries are essential structures for managing key–value mappings in Python. With fast lookups, flexible value types, and a rich method set, they excel at storing dynamic or nested data and powering associative logic in applications.