python使用lambda在条件列表中更改dict中的值

2024-09-25 02:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种使用lambda或列表理解来更改列表中字典中的值的方法

假设我有一个简单的字典列表

list_of_objects = [
 {'note': 'note1', 'comments': 'Test comments', elem': 1},
 {'note': 'note2','comments': None, elem': 2}
]

我需要遍历这个列表,找到每个dict中的每个值,并将其替换为文本“未提供任何注释”

预期结果:

[{'note': 'note1',
  'comments': 'Test comments'
  'elem': 1},
 {'note': 'note2',
  'comments': 'No comments was provided'
  'elem': 2}]

我可以使用标准for循环操作来完成。但是我正在寻找一个机会,我们lambda或列表理解,以尽量减少我的代码


Tags: of方法lambdatestnone列表字典objects
1条回答
网友
1楼 · 发布于 2024-09-25 02:24:15

见下文(我认为for循环带来更好的可读性)

list_of_objects = [
    {'note': 'note1', 'comments': 'Test comments', 'elem': 1},
    {'note': 'note2', 'comments': None, 'elem': 2}
]

lst = [{k: v if k != 'comments' else v if v else 'no comments' for k, v in entry.items()} for entry in
       list_of_objects]
print(lst)

输出

[{'note': 'note1', 'comments': 'Test comments', 'elem': 1}, {'note': 'note2', 'comments': 'no comments', 'elem': 2}]

相关问题 更多 >