Explain Codes LogoExplain Codes Logo

Create a dictionary with comprehension

python
dict-comprehensions
python-3.7
performance-tips
Alex KataevbyAlex Kataev·Aug 26, 2024
TLDR

To quickly construct a dictionary in Python using comprehension, use the {key: value for (key, value) in iterable} template. Below we use a classic example:

dict_comp = {n: n * 2 for n in range(4)} # Multiply by two because we love maths

In this case, dict_comp becomes {0: 0, 1: 2, 2: 4, 3: 6}, with the numbers as keys and their doubles as values.

Digging deeper: Mastering dict comprehensions

Understanding the nuances

  • Order preservation: From Python 3.7 on, dictionaries remember the insertion order. So, the order in comprehension is the order.

  • Unique keys: Beware, keys in dictionaries must be unique. If you don't pay attention, a key can overwrite another!

  • Filtering: Dict comprehensions can do some spring cleaning by filtering out entries:

    # Dict, but make it clean {k: v for k, v in some_dict.items() if v is not None}

Using the dict constructor and zip function

  • If we have two lists and we want a dictionary out of them, the dict() constructor got us covered:

    # 'Zip' them together and they can't run away simple_dict = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
  • But wait, it's not over yet! You can alter the values in the dict constructor:

    # No need for a gym membership, we lift +10s here modified_dict = dict((k, v + 10) for k, v in zip(keys, values))

Advanced comprehension patterns in action

  • You can combine advanced filtering and value modification in a comprehension to create more complex dictionaries. Who said Python wasn't a workout for your brain?

    # Putting the 'even' in 'even more fun' {k: v * v for k, v in zip(range(5), range(5, 10)) if v % 2 == 0}
  • Generator expressions with dict() are the way to go for creating dictionaries on the fly when handling large datasets:

    # Don't worry, it won't bite... unless you're a performance issue large_dict = dict((i, i**2) for i in range(1000))

Making dictionaries in older Python versions

In Python 2.7 and below, dict comprehensions don't exist. However, worry not, there are other ways:

# Constructing a dictionary the old-fashioned way legacy_dict = {} for key, value in zip(keys, values): legacy_dict[key] = value

Or use tuple unpacking in the dict() constructor for a more elegant solution:

# Unpacking surprises! legacy_dict = dict((key, value) for key, value in zip(keys, values))

Getting top performance

  • Built-in functions: Use these instead of coding from scratch. Python loves efficiency!
  • Nested expressions: Avoid inserting complex expressions within loops in comprehensions. They can give performance hiccups.
  • Particularly for large datasets, consider the cost of memory usage and computing power.
  • Overlapping keys? Dict comprehensions don't check for that. It’s not a bug, it's a feature!