我有一個字典串列,我需要過濾該串列,其中某個鍵具有某個值。例如,只有dicts'name'是'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]
# <output>
[{'name': 'Joel', 'age': 48, 'brother': 'Tommy'},
{'name': 'Tommy', 'age': 43, 'brother': 'Joel'},
{'name': 'Ellie', 'age': 14, 'brother': None}]
期望的輸出:
[{'name': 'Joel', 'age': 48, 'brother': 'Tommy'},
{'name': 'Ellie', 'age': 14, 'brother': None}]
uj5u.com熱心網友回復:
您可以嘗試以下代碼,這可能會對您有所幫助:
[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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447794.html
