DEV Community

Pinei
Pinei

Posted on

Reformatting dictionaries in Python

Today we'll explore a common problem when working with lists of dictionaries in Python: the need to filter those dictionaries based on a specific set of keys. We'll present two concise and efficient solutions, utilizing powerful features of the language.

The problem

Imagine you have a list of dictionaries, where each dictionary represents a set of parameters. In some situations, you need to extract only the attributes (key-value pairs) that correspond to a subset of keys.

Example:

parameters = [
  { "start": "2020-01", "end": "2020-02", "done": True },
  { "start": "2020-02", "end": "2020-03", "done": True }
]

keys = ['start', 'end']

filtered_parameters = filter_dictionaries(parameters, keys)
print(filtered_parameters)

# Expected output:
# [{'start': '2020-01', 'end': '2020-02'},
#  {'start': '2020-02', 'end': '2020-03'}]
Enter fullscreen mode Exit fullscreen mode

Our goal is to get a new list of dictionaries, containing only the "start" and "end" attributes from each original dictionary.

Solution 1: Traditional iteration with if

The first approach uses a for loop to iterate over the list of dictionaries and another nested for loop to iterate over the desired keys. Inside the inner loop, we check if the key exists in the current dictionary and, if so, add the key-value pair to the new dictionary.

def filter_dictionaries(parameters, keys):
  result = []
  for dictionary in parameters:
    new_dict = {}
    for key in keys:
      if key in dictionary:
        new_dict[key] = dictionary[key]
    result.append(new_dict)
  return result
Enter fullscreen mode Exit fullscreen mode

Solution 2: List Comprehension for the rescue

Python offers a powerful feature called list comprehension, which allows you to create lists and dictionaries concisely and expressively. We can use list comprehension to implement dictionary filtering in virtually a single line of code:

def filter_dictionaries(parameters, keys):
  return [
    {
      key: dictionary[key]
        for key in keys if key in dictionary
    } for dictionary in parameters
  ]
Enter fullscreen mode Exit fullscreen mode

This approach is more compact and, for many developers, more readable than the version with nested loops.

Comparing approaches

Both solutions are efficient and produce the same result. The choice between them is a matter of personal preference. Some may find the list comprehension version more elegant and concise, while others may prefer the clarity of traditional iteration.

Tip: When working with lists and dictionaries, prioritize the use of list comprehension to write cleaner and more precise code.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs