为了账号安全,请及时绑定邮箱和手机立即绑定

在for循环中比较python中JSON对象的值

在for循环中比较python中JSON对象的值

Cats萌萌 2023-06-20 10:26:01
我有一个 JSON 格式的对象,它是我从 API 主体的用户那里收到的。当在 Python 中存储并检查其类型时,它显示为 dict。但是字典中的键是作为一个集合存储的。x = {'test': {'shipmentInfo': {'Ready Date', 'Ready Time', 'Delivery Date', 'Service Level'}}}我将字典的所有键存储在如下列表中check_list = ["test", "shipmentInfo", "Ready Date","Ready Time","Delivery Date","Service Level"]我正在编写一个简单的条件来检查字典中给出的每个键是否都出现在我的列表中。如果任何密钥不存在,它应该说密钥丢失missing = [field for field in x if field not in check_list]   if len(missing) == 0:       print("All values are entered")   else:       [print(f"Missing value: {field}") for field in missing]我的情况的问题是,它只是检查字典中是否存在“测试”。它没有检查我需要的主要密钥(“就绪日期”、“就绪时间”、“交货日期”、“服务级别”)。如果我从列表中删除一个值,比如交货日期("Ready Date","Ready Time","Service Level")我使用的逻辑会给我这个结果All values are entered如何获取(“就绪日期”、“就绪时间”、“交货日期”、“服务水平”)并将其与我的列表进行比较?
查看完整描述

1 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

这些值{'Ready Date', 'Ready Time', 'Delivery Date', 'Service Level'}组成一个集合,它们不是内部字典的键,但仍然可以检查它们是否存在于原始字典中x:


已实现的dictionary_to_list函数采用原始字典x并将其展平为一个列表,该列表包含列表中的所有键和值。


x = {'test': {'shipmentInfo': {'Ready Date', 'Ready Time', 'Delivery Date', 'Service Level'}}}

check_list = ["test", "shipmentInfo", "Ready Date","Ready Time","Delivery Date","Service Level"]



def dictionary_to_list_helper(d, l):

    for k, v in d.items():

        l.append(k)

        if isinstance(v, list) or isinstance(v, set):

            for item in v:

                l.append(item)

        elif isinstance(v, dict):

            dictionary_to_list_helper(v, l)


def dictionary_to_list(d):

    l = []

    dictionary_to_list_helper(d, l)

    return l


missing = [field for field in dictionary_to_list(x) if field not in check_list]

if len(missing) == 0:

   print("All values are entered")

else:

   [print(f"Missing value: {field}") for field in missing]


查看完整回答
反对 回复 2023-06-20
  • 1 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信