在字典列表中查找值并返回字典的ID

时间:2019-09-23 19:37:35

标签: python

我想尝试查找一个值是否在字典列表中,这可以通过以下操作轻松完成:

if any(x['aKey'] == 'aValue' for x in my_list_of_dicts):

但这只是一个布尔响应,我不仅要检查值是否存在,还要在以后访问它,所以类似:

for i, dictionary in enumerate(my_list_of_dicts):
    if dictionary['aKey'] == 'aValue':
        # Then do some stuff to that dictionary here
        # my_list_of_dicts[i]['aNewKey'] = 'aNewValue'

是否有更好/更多的pythonic方式写出来?

2 个答案:

答案 0 :(得分:1)

使用next函数,如果期望仅找到一个 target 字典:

my_list_of_dicts = [{'aKey': 1}, {'aKey': 'aValue'}]
target_dict = next((d for d in my_list_of_dicts if d['aKey'] == 'aValue'), None)
if target_dict: target_dict['aKey'] = 'new_value'

print(my_list_of_dicts)

输出(带有更新的词典的输入列表):

[{'aKey': 1}, {'aKey': 'new_value'}]

答案 1 :(得分:0)

您可以使用列表推导。这将返回符合您条件的词典列表。

[x for x in my_list_of_dicts if x['aKey']=='aValue' ]
相关问题