Learning

Dictionaries Mastery

Dictionaries Mastery

Creating Dictionaries

python
# 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}

Accessing Values

python
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}

Modifying Dictionaries

python
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 dict

Iteration Methods

python
d = {'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}')

Dictionary Comprehension

python
# 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()}

Nested Dictionaries

python
users = { 'u1': {'name': 'Alice', 'role': 'admin'}, 'u2': {'name': 'Bob', 'role': 'user'} } print(users['u1']['name']) # Alice
Key Rules
  • •Use d.get(key, default) instead of d[key] to avoid KeyError on missing keys
  • •setdefault() is like get() but it ALSO inserts the key with the default value if it's missing
  • •Always use d.items() to iterate over both keys and values simultaneously
  • •dict.update() can take another dict or keyword arguments to update multiple keys at once
  • •Dictionary comprehension syntax: {key_expr: val_expr for item in iterable if condition}
Your Task

Create 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.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should define invert_dict function
Should use setdefault or manual check for grouping
Should define deep_get function
Should use isinstance check in deep_get
Should test with nested dictionary
Should handle invalid path returning default