赋值时Python try/pass?

2024-04-19 22:28:52 发布

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

情况: 当给定的HashKey通过url发送到视图时,Django视图从服务器(Amazon的DynamoDB表)获取数据项。你知道吗

问题: 因为它是一个非关系数据库,DynamoDB表中的某些项缺少其他项可能具有的键-->;对于某些获取尝试,会引发一个KeyError,这意味着如果我在视图中分配一个dictionary,它会因为该KeyError而停止整个过程。这意味着对于每次获取尝试(字典值赋值),我必须尝试/except KeyError。你知道吗

问题: 是否有python语法允许在赋值时在同一行上使用try/except?比如:

'times_a_day': try jsonFormatIndications[elem]['times_a_day']) except: pass

谢谢你!你知道吗


Tags: django服务器视图urlamazon情况dynamodb关系数据库
1条回答
网友
1楼 · 发布于 2024-04-19 22:28:52

不,不能一行就完成。

您可以使用^{}和函数在一行中优雅地处理所有情况。

get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

我们可以定义一个名为get_nested_key_value()的泛型函数,它将使用3个参数my_dictouter_keyinner_key来获取所需的值。你知道吗

my_dict:正在执行查找的字典
outer_keyelem在这种情况下
inner_key:在elem字典中查找的键(本例中为times_a_day

我们首先检查字典中是否存在elem,如果存在,然后使用.get()检查times_a_day是否存在。如果存在,我们将返回值。否则,返回None。你知道吗

def get_nested_key_value(my_dict, outer_key, inner_key):
    if my_dict.get(outer_key) and my_dict[outer_key].get(inner_key): # check if both keys present
        return my_dict[outer_key][inner_key] # return the required value
    return None # return None if key not found

然后您可以调用函数,该函数将在找到键的情况下返回值,否则None。你知道吗

'times_a_day' : get_nested_key_value(jsonFormatIndications, elem, 'times_a_day')

相关问题 更多 >