-1

I only found questions where people wanted to copy a dictionary to another depending on some keys but not for a list of dictionaries.

Lets say I have a List containing dictionaries

myList = [
  {'version': 'v1', 'updated': '2020-06-17 22:15:00+00:00', 'name': 'alpha'},
  {'version': 'v5', 'updated': '2019-08-30 11:42:00+00:00', 'title': 'gamma'},
  {'version': 'v7', 'updated': '2020-06-17 22:15:00+00:00', 'name': 'eta'}
]

now I want to create a new List of dictionaries with only keeping the keys version and updated. There is a high chance that the dictionaries also have some keys different from each other like it is shown in myList with name and title. But that shouldn't bother me as I know that the keys I want to filter with are the same in every dictionary. So it is important for me to use version and updated and not something like dropping everything with name or title. The result should be a new list of dictionaries

myFilteredList= [
  {'version': 'v1', 'updated': '2020-08-24 17:37:00+00:00'},
  {'version': 'v5', 'updated': '2019-08-30 11:42:00+00:00'},
  {'version': 'v7', 'updated': '2020-06-17 22:15:00+00:00'}
]
matlabalt
  • 40
  • 6
  • Does this answer your question? [Filter dict to contain only certain keys?](https://stackoverflow.com/questions/3420122/filter-dict-to-contain-only-certain-keys) – mkrieger1 Jun 10 '21 at 11:46
  • Where is the date `2020-08-24` supposed to come from in the result? – mkrieger1 Jun 10 '21 at 11:48

2 Answers2

1

You can use a dict comprehension to filter within a list comprehension for each dictionary. Basically check if the key is in your desired set, and if so, keep that pair in your newly generated dict.

>>> [{k:v for k,v in d.items() if k in {'version', 'updated'}} for d in myList]
[{'version': 'v1', 'updated': '2020-06-17 22:15:00+00:00'},
 {'version': 'v5', 'updated': '2019-08-30 11:42:00+00:00'},
 {'version': 'v7', 'updated': '2020-06-17 22:15:00+00:00'}]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

You can create new list of dictionaries with those keys

myFilteredList = [{'version': d.get('version'), 'updated': d.get('updated')} for d in myList]

# [{'version': 'v1', 'updated': '2020-06-17 22:15:00+00:00'},
#  {'version': 'v5', 'updated': '2019-08-30 11:42:00+00:00'},
#  {'version': 'v7', 'updated': '2020-06-17 22:15:00+00:00'}]
Guy
  • 46,488
  • 10
  • 44
  • 88