简体   繁体   English

根据以键为过滤器的字典列表创建字典列表

[英]Create List of Dictionaries depending from a list of dictionary with key as filter

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 .现在我想创建一个新的字典列表,只保留键versionupdated 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 .字典很有可能也有一些彼此不同的键,就像在myList中显示的那样,带有nametitle 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 .因此,使用versionupdated对我来说很重要,而不是像删除所有带有nametitle的东西。 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'}
]

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM