Loop through all nested dictionary values?

前端 未结 12 1363
温柔的废话
温柔的废话 2020-11-22 09:16
for k, v in d.iteritems():
    if type(v) is dict:
        for t, c in v.iteritems():
            print \"{0} : {1}\".format(t, c)

I\'m trying to l

12条回答
  •  深忆病人
    2020-11-22 09:48

    These answers work for only 2 levels of sub-dictionaries. For more try this:

    nested_dict = {'dictA': {'key_1': 'value_1', 'key_1A': 'value_1A','key_1Asub1': {'Asub1': 'Asub1_val', 'sub_subA1': {'sub_subA1_key':'sub_subA1_val'}}},
                    'dictB': {'key_2': 'value_2'},
                    1: {'key_3': 'value_3', 'key_3A': 'value_3A'}}
    
    def print_dict(dictionary):
        dictionary_array = [dictionary]
        for sub_dictionary in dictionary_array:
            if type(sub_dictionary) is dict:
                for key, value in sub_dictionary.items():
                    print("key=", key)
                    print("value", value)
                    if type(value) is dict:
                        dictionary_array.append(value)
    
    
    
    print_dict(nested_dict)
    

提交回复
热议问题