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

我有一个 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

如何获取(“就绪日期”、“就绪时间”、“交货日期”、“服务水平”)并将其与我的列表进行比较?


Cats萌萌
浏览 118回答 1
1回答

慕容3067478

这些值{'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 lmissing = [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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python