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 languag…


This content originally appeared on DEV Community and was authored by Pinei

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'}]

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

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
  ]

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.


This content originally appeared on DEV Community and was authored by Pinei


Print Share Comment Cite Upload Translate Updates
APA

Pinei | Sciencx (2025-02-12T23:28:24+00:00) Reformatting dictionaries in Python. Retrieved from https://www.scien.cx/2025/02/12/reformatting-dictionaries-in-python/

MLA
" » Reformatting dictionaries in Python." Pinei | Sciencx - Wednesday February 12, 2025, https://www.scien.cx/2025/02/12/reformatting-dictionaries-in-python/
HARVARD
Pinei | Sciencx Wednesday February 12, 2025 » Reformatting dictionaries in Python., viewed ,<https://www.scien.cx/2025/02/12/reformatting-dictionaries-in-python/>
VANCOUVER
Pinei | Sciencx - » Reformatting dictionaries in Python. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/02/12/reformatting-dictionaries-in-python/
CHICAGO
" » Reformatting dictionaries in Python." Pinei | Sciencx - Accessed . https://www.scien.cx/2025/02/12/reformatting-dictionaries-in-python/
IEEE
" » Reformatting dictionaries in Python." Pinei | Sciencx [Online]. Available: https://www.scien.cx/2025/02/12/reformatting-dictionaries-in-python/. [Accessed: ]
rf:citation
» Reformatting dictionaries in Python | Pinei | Sciencx | https://www.scien.cx/2025/02/12/reformatting-dictionaries-in-python/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.