【发布时间】:2018-01-16 03:20:22
【问题描述】:
我正在使用 python 3.5。函数1是:
def boolean_key_validation(dictionary, key):
data = {}
try:
dictionary_value = dictionary[key]
except KeyError:
pass
else:
if dictionary_value == 'TRUE':
data[key] = True
elif dictionary_value == 'FALSE':
data[key] = False
else:
raise ValueError("{} value should be either blank or 'TRUE'/'FALSE' only".format(key))
return data[key] # not able to get the 'do_nothing' value here
功能2是:
def read_file(start_date, end_date, dictionary):
read_data = {}
files = File.objects.all()
# ... #
read_data['downloaded'] = boolean_key_validation(dictionary, 'downloaded')
read_data['integrity'] = boolean_key_validation(dictionary, 'integrity')
read_data['validation'] = boolean_key_validation(dictionary, 'validation')
return files.filter(**read_data)
我想根据“已下载”的布尔值等过滤模型“文件”。 在函数 1 中,我想要的是,如果字典中不存在键,则函数 1 不应该执行任何操作,函数 2 中的 read_data 字典应该没有该键的值。
我已经搜索过类似的问题,但那些在某些函数的条件语句中使用了“pass”。
编辑:
以下是我输入大量布尔值的主要功能,我必须为每个键编写单独的 try-catch。因此,创建了“boolean_key_validation”来验证那些大量的键并缩短我的主要功能。这里的“通过”正在完成它的工作,但我的 function1 无法给我这种回报。
如果字典中不存在键,我只想将其从 read_data 中省略。
def read_file(start_date, end_date, dictionary):
read_data = {}
files = File.objects.all()
# try-catch for checking 'downloaded'.
# have to write these conditions for other boolean values also and thats why created function1.
try:
dictionary_value = dictionary['downloaded']
except KeyError:
pass
else:
if dictionary_value.upper() == 'TRUE':
read_data['downloaded'] = True
elif dictionary_value.upper() == 'FALSE':
read_data['downloaded'] = False
else:
raise ValueError("downloaded value should be either blank or 'TRUE'/'FALSE' only")
# try catch for 'integrity' and 'validation' etc. #
return files.filter(**read_data)
【问题讨论】:
-
密钥没有值是指
None。 -
不不不。我的意思是我在 function2 中的 files.filter() 将没有那个键来在 File 模型上应用过滤器。
-
为什么不直接使用
'downloaded' in dictionary.keys()?这会立即为您提供 True/False 值。 -
我会试试这个。
-
@Idlehands,如果密钥不存在,那么我希望它省略进入我的过滤器()。 True/False 值将仅根据这些值进行过滤。我已经编辑了完整的上下文问题。如果还不清楚,请告诉我。
标签: python django dictionary