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

问题描述

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

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

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

我需要遍历这个列表,用 None 找到每个字典中的每个值,并用文本“没有提供评论”替换这个值

预期结果:

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

我可以使用标准的循环操作来做到这一点。但是我们正在寻找机会使用 lambda 或列表理解来最小化我的代码

解决方法

见下文(我认为 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': 'no comments','elem': 2}]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...