Check nested dictionary values?

前端 未结 3 930
别跟我提以往
别跟我提以往 2020-12-28 09:38

For a large list of nested dictionaries, I want to check if they contain or not a key. Each of them may or may not have one of the nested dictionaries, so if I loop this sea

3条回答
  •  醉梦人生
    2020-12-28 10:19

    Here's a generalization for an arbitrary number of keys:

    for Dict1 in DictionariesList:
        try: # try to get the value
            reduce(dict.__getitem__, ["Dict2", "Dict3", "Dict4"], Dict1)
        except KeyError: # failed
            continue # try the next dict
        else: # success
            print("Yes")
    

    Based on Python: Change values in dict of nested dicts using items in a list.

提交回复
热议问题