简体   繁体   中英

comparing values from a JSON object in python in a for loop

I have a JSON format object, that I receive from a user from an API body. When stored and checked its type in Python it says dict. But the keys within the dict are stored as a set.

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

I am storing all the keys of a dictionary in a list as below

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

I am writing a simple condition to check if every key given in the dictionary is present in my list. If any key is not present it should say that key is missing

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]

the problem with my condition is, it is only checking if 'test' is present in the dictionary. It is not checking for the main keys that I need("Ready Date","Ready Time","Delivery Date","Service Level"). If i remove one value from the list, like delivery date

("Ready Date","Ready Time","Service Level")

the logic I use will give me this result

All values are entered

How to fetch ("Ready Date","Ready Time","Delivery Date","Service Level") and compare it with my list?

The values {'Ready Date', 'Ready Time', 'Delivery Date', 'Service Level'} are composing a set, they are not keys of an inner dictionary, but it is still possible to check if they exist in the original dictionary x :

The implemented dictionary_to_list function, takes the original dictionary x and flattens it into a list that contains all keys and values of it to a list.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM