Dictionaries store key-value pairs with {}. Keys must be immutable and unique.
Access
dict[key] or dict.get(key, default)
Methods
keys(),values(),items()update(),pop(),setdefault()
Dictionaries store key-value pairs with {}. Keys must be immutable and unique.
dict[key] or dict.get(key, default)
keys(), values(), items()update(), pop(), setdefault()person = {"name": "Alice", "age": 25}
print(person["name"])
print(person.get("phone", "N/A"))
person["email"] = "alice@mail.com"
for k, v in person.items():
print(f"{k}: {v}")
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print("Name:", person["name"])
print("Get:", person.get("email", "not found"))
# Add / update
person["email"] = "alice@example.com"
print("Updated keys:", list(person.keys()))
# Iterate
for key, value in person.items():
print(f"{key}: {value}")
# Nested
company = {
"name": "SukhNexus",
"employees": [
{"name": "Bob", "role": "Developer"},
{"name": "Eve", "role": "Designer"}
]
}
print("Role:", company["employees"][0]["role"])
Count character frequencies in a string.
text = "hello"
for c in set(text):
print(f"{c}: {text.count(c)}")
What does dict[key] do for missing keys?
Raises KeyError. Use .get() for safe access.
Hash tables map keys to storage locations via hash functions.