如何通过访问另一个对象(如果存在)来添加新值



我在想这个问题。如何在不出错的情况下向该对象添加新值?

data = {
'attributes': processed_data['attributes'],
'categories': processed_data['categories'],
'filters': processed_data['filters'],
'min_price': processed_data['min_price'],
'max_price': processed_data['max_price'],
'session_id': processed_data['session_id'],
'new_value': process_data['new_value'],  # this value will not always exist
'client_id': session.clientId
}

在javascript中,我会使用三元运算符但我不知道如何在python 中继续

最简单的方法是先生成具有所有保证值的dict,然后使用if语句来选择性地添加更多内容。

mydict = {
'key1': value1,
'key2': value2,
'key3': value3
}
if some_condition:
mydict['key4'] = value4

您可以使用get方法(https://docs.python.org/3/library/stdtypes.html?highlight=dict%20get#dict.get)。

'new_value': process_data.get('new_value')

这将检查process_data是否具有密钥new_value。否则,它将把data['new_value']设置为None,而不引发KeyError

您只需要这样做,因为这是一个字典:

data['new_value'] = your_value_here

只需执行if条件即可检查值是否存在!

If语句:

if 'new_value' in process_data:
data['new_value'] = process_data['new_value']

三元运算符:

data['new_value'] = process_data['new_value'] if 'test' in process_data else -1

.get((函数(最佳(:

# second argument is the default if it doesn't exist
data['new_value'] = process_data.get('new_value', -1)  

get((方法返回具有指定键的项的值,如果指定键不存在,则可以设置要返回的值(默认值为None(

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.get("price", 15000)

https://www.w3schools.com/python/ref_dictionary_get.asp

相关内容

最新更新