我从通常以 JSON 格式提供的用户 API 请求(来自 API 正文)中获取一些数据有效负载。它作为字典存储在我的 python 代码中。"Data":{ "Ready Date":"2020-01-31T12:00:00", "Ready Time":"2020-01-31T12:00:00", "Delivery Date":"2020-02-15T12:00:00", "Service Level":"EC", "Close Time":"2020-01-31T17:00:00"}我想验证给定的字段。如果用户没有给出“就绪日期”,它应该说缺少就绪日期并检查该 JSON 中的每个对象并说明是否缺少某些内容我的代码:我将所有字典键存储在一个数组中,例如:a = ["Ready Date","Ready Time","DeliveryDate","Service Level","Close Time"]我的逻辑for value in data: if value not in a: print("value Missing" : Value) else: print("All values are entered")结果:如果我给字典和列表中的所有值都一样,My results prints :All values are enteredAll values are enteredAll values are entered如果我从字典中删除任何值并检查条件,我会得到以下打印结果value missing : Ready DateAll values are enteredAll values are entered我需要避免循环并且只打印一次
1 回答
子衿沉夜
TA贡献1828条经验 获得超3个赞
你不应该在没有首先提供你尝试过的证据的情况下提出问题(尽管你没有提出问题你给了任务),但答案如下:
data = {
"Ready Date":"2020-01-31T12:00:00",
"Ready Time":"2020-01-31T12:00:00",
"Delivery Date":"2020-02-15T12:00:00",
"Service Level":"EC",
"Close Time":"2020-01-31T17:00:00"}
a = ["Ready Date","Ready Time","DeliveryDate","Service Level","Close Time"]
missing = [field for field in a if field not in data]
if len(missing) == 0:
print("All values are entered")
else:
[print(f"Missing value: {field}") for field in missing]
添加回答
举报
0/150
提交
取消