How to extract a subset of key-value pairs from dictionary?
In Python, dictionaries are one of the most versatile data structures for storing key-value pairs. Often, you’ll need just a portion of the dictionary—whether for filtering, data wrangling, or other tasks. Extracting a subset can be done in a few succinct ways, as shown below.
1. Dictionary Comprehension
A dictionary comprehension is a concise, Pythonic way to create a new dictionary from an existing one. Here’s a typical use case when you already know which keys you want to extract:
original_dict = { 'name': 'Alice', 'age': 25, 'city': 'New York', 'job': 'Engineer' } keys_to_extract = ['name', 'city'] subset_dict = {k: original_dict[k] for k in keys_to_extract if k in original_dict} print(subset_dict) # Output: {'name': 'Alice', 'city': 'New York'}
k in original_dict
ensures that we don’t get aKeyError
ifkeys_to_extract
contains keys not found inoriginal_dict
.- The result is a new dictionary, leaving the original untouched.
2. Using Set Intersection
If you have a larger dictionary and a separate set of keys, you can also leverage set intersection to streamline the process:
original_dict = { 'name': 'Alice', 'age': 25, 'city': 'New York', 'job': 'Engineer' } keys_to_extract = {'age', 'city', 'country'} # 'country' doesn't exist in original_dict valid_keys = original_dict.keys() & keys_to_extract # set intersection subset_dict = {k: original_dict[k] for k in valid_keys} print(subset_dict) # Output: {'age': 25, 'city': 'New York'}
original_dict.keys() & keys_to_extract
returns the intersection of two sets.- This method is helpful when you’re dealing with potentially large dictionaries or uncertain key sets.
3. Filtering with Conditions
Sometimes you need to filter based on a condition rather than a predefined list of keys. In that case, you can use a dictionary comprehension with an if
clause:
original_dict = { 'item1': 10, 'item2': 25, 'item3': 30, 'item4': 15 } # Extract only those pairs where the value is >= 20 subset_dict = {k: v for k, v in original_dict.items() if v >= 20} print(subset_dict) # Output: {'item2': 25, 'item3': 30}
- This approach can be adapted to any custom logic—based on key patterns, value ranges, or both.
Additional Tips
- Performance: Dictionary comprehensions and set operations are generally efficient and concise for creating subsets.
- Safety: Always consider whether a key might not exist in the dictionary. Using conditionals or set intersection helps avoid
KeyError
. - In-place vs. Copy: Python dictionaries are mutable, so always clarify if you’re creating a new dictionary or modifying an existing one. The examples above create new ones.
Level Up Your Python Skills
Working with dictionaries is just one component of Python mastery. If you’re keen to build robust applications or excel in interviews, here are some top resources from DesignGurus.io:
-
Grokking Python Fundamentals
A comprehensive course for anyone looking to strengthen their Python foundations, including data structures like dictionaries, lists, and more. -
Grokking the Coding Interview: Patterns for Coding Questions
Perfect if you’re aiming to ace coding interviews. It focuses on the essential patterns found in real-world interview problems, many of which can be solved elegantly using Python’s dictionary operations.
If you’re tackling large-scale system challenges, consider:
- Grokking System Design Fundamentals
An excellent primer for those aspiring to build highly scalable, fault-tolerant systems—a critical skill for senior technical roles.
Final Thoughts
Extracting a subset of key-value pairs from a dictionary can be done in multiple ways—dictionary comprehensions, set intersections, and filtering with conditionals being the most common. Each approach is clean, efficient, and helps maintain code readability. By combining these Python tricks with a deeper understanding of coding patterns and system design, you’ll be well-prepared for both day-to-day software development and high-stakes technical interviews.
Happy Coding!