Review and test your knowledge of Python dictionaries with comprehensive questions and answers. Practice key concepts like key-value pairs, dictionary methods, and data manipulation to strengthen your Python programming skills. Ideal for beginners and students preparing for exams or interviews.
- Dictionaries are unordered (before Python 3.7) collections of key-value pairs - Keys must be unique and immutable (strings, numbers, tuples) - Values can be any Python object - Unlike lists, dictionaries are accessed by keys rather than indices - Dictionaries are optimized for fast lookups by key - They use curly braces {} instead of square brackets []
- "Creating: `d = {'name': 'Alice', 'age': 25}`" - "Accessing: `d['name']` returns 'Alice'" - "Checking keys: `'age' in d` returns `True`"
1. `get(key[, default])`: Safely retrieves a value, returns None or default if key doesn't exist 2. `items()`: Returns view of (key, value) pairs for iteration 3. `update()`: Merges another dictionary into current one
- "`ages.get('Bob', 0)` returns 0 if 'Bob' not in dictionary" - "`for k, v in my_dict.items():` iterates through pairs" - "`dict1.update(dict2)` adds dict2's items to dict1"
- Direct access (`dict[key]`) raises KeyError if missing - `get()` method returns None or specified default - `setdefault()` both checks and sets default if missing - `collections.defaultdict` automatically handles missing keys - `try/except` blocks can catch KeyError
- "`value = my_dict.get('missing', 'default')`" - "`value = my_dict.setdefault('new_key', [])`" - "`from collections import defaultdict; d = defaultdict(int)`"
- Compact way to create dictionaries from iterables - Similar to list comprehensions but produces key-value pairs - Syntax: `{key_expr: value_expr for item in iterable}` - Can include conditional statements - Often more readable than traditional loops
- "`{x: x**2 for x in range(5)}` creates {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}" - "`{k: v.upper() for k, v in d.items() if len(v) > 3}` filters and transforms"
- When you need to associate keys with values (mappings) - For fast lookups by unique identifiers - When data is naturally key-value pairs (like JSON) - For counting occurrences (using keys as items) - When order matters (Python 3.7+ maintains insertion order) - For implementing sparse data structures
- "Storing user profiles with usernames as keys" - "Counting word frequencies: `{'the': 15, 'a': 7}`" - "Representing graph adjacency lists"
Tutorials, Roadmaps, Bootcamps & Visualization Projects