# Literal syntax
person = {
'name': 'Alice',
'age': 30,
'city': 'New York'
}
# Constructor
empty = dict()
from_pairs = dict([('a', 1), ('b', 2)]) # {'a': 1, 'b': 2}
from_kwargs = dict(name='Bob', age=25) # {'name': 'Bob', 'age': 25}
# fromkeys (all keys get same value)
keys = ['a', 'b', 'c']
d = dict.fromkeys(keys, 0) # {'a': 0, 'b': 0, 'c': 0}d = {'x': 10, 'y': 20}
# Square brackets (KeyError if missing!)
print(d['x']) # 10
# print(d['z']) # KeyError!
# get() method (Returns None or default if missing)
print(d.get('y')) # 20
print(d.get('z')) # None
print(d.get('z', 99)) # 99
# setdefault (Get value, or INSERT if missing)
val = d.setdefault('z', 99)
# d is now {'x': 10, 'y': 20, 'z': 99}d = {'a': 1, 'b': 2}
# Add / Update
d['c'] = 3 # Add new
d['a'] = 100 # Update existing
d.update({'d': 4, 'a': 200}) # Update multiple
# Delete
del d['b'] # Deletes key 'b' (KeyError if missing)
val = d.pop('c') # Removes 'c' and returns 3
val = d.pop('z', None) # Safe pop with default
d.clear() # Empty the dictd = {'name': 'Alice', 'age': 30, 'city': 'NYC'}
# Keys (default iteration)
for key in d:
print(key)
for key in d.keys():
print(key)
# Values
for val in d.values():
print(val)
# Key-Value Pairs (most common!)
for key, val in d.items():
print(f'{key}: {val}')# Basic
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# With condition
evens = {x: x**2 for x in range(10) if x % 2 == 0}
# Transform existing dict
prices = {'apple': 1.2, 'banana': 0.5}
taxed = {k: round(v * 1.1, 2) for k, v in prices.items()}
# Invert dict (values must be unique!)
original = {'a': 1, 'b': 2}
inverted = {v: k for k, v in original.items()}users = {
'u1': {'name': 'Alice', 'role': 'admin'},
'u2': {'name': 'Bob', 'role': 'user'}
}
print(users['u1']['name']) # AliceCreate a function `invert_dict(d)` that inverts a dictionary. If the original dict has duplicate values, group the keys into a list (e.g., {'a': 1, 'b': 1} → {1: ['a', 'b']}). Create a function `deep_get(d, keys, default=None)` that safely accesses nested dictionaries, e.g., deep_get(d, ['a', 'b', 'c']) without throwing KeyError.