簡體   English   中英

從字典列表中過濾鍵值

[英]Filter key-values from a list of dictionaries

我有一個字典列表,我需要過濾某個鍵具有特定值的列表。 例如,只有dict s where 'name' is 'Joel' or 'Ellie'

dict1 = {'name': 'Joel', 'age': 48, 'brother': 'Tommy'}
dict2 = {'name': 'Tommy', 'age': 43, 'brother': 'Joel'}
dict3 = {'name': 'Ellie', 'age': 14, 'brother': None}

list_of_dicts = [dict1, dict2, dict3]

# <output>
[{'name': 'Joel', 'age': 48, 'brother': 'Tommy'},
{'name': 'Tommy', 'age': 43, 'brother': 'Joel'},
{'name': 'Ellie', 'age': 14, 'brother': None}]

所需的 output:

[{'name': 'Joel', 'age': 48, 'brother': 'Tommy'},
{'name': 'Ellie', 'age': 14, 'brother': None}]

您可以嘗試以下代碼,這可能對您有所幫助:

[value for value in list_of_dicts if value.get('name') in ['Joel', 'Ellie']]

所以你的代碼將是:

dict1 = {'name': 'Joel', 'age': 48, 'brother': 'Tommy'}
dict2 = {'name': 'Tommy', 'age': 43, 'brother': 'Joel'}
dict3 = {'name': 'Ellie', 'age': 14, 'brother': None}

list_of_dicts = [dict1, dict2, dict3]
final_list = [value for value in list_of_dicts if value.get('name') in ['Joel', 'Ellie']]
print(final_list)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM