可以使用Python中的条件表达式或字典的get方法,从部分对象中条件获取键的值并进行赋值。
示例代码1:使用条件表达式
person = {
"name": "John",
"age": 30,
"gender": "male"
}
person["height"] = 175 if "height" in person else 0
print(person)
输出:
{'name': 'John', 'age': 30, 'gender': 'male', 'height': 0}
示例代码2:使用字典的get方法
person = {
"name": "John",
"age": 30,
"gender": "male"
}
person["height"] = person.get("height") or 0
print(person)
输出:
{'name': 'John', 'age': 30, 'gender': 'male', 'height': 0}
在这两个示例中,如果要分配的密钥不存在,则通过条件表达式或get方法将此键的值设置为特定值(在此示例中为0)。
上一篇:部分对特定行进行分组并更新表格