Loop through all nested dictionary values?

前端 未结 12 1255
温柔的废话
温柔的废话 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:57

    Slightly different version I wrote that keeps track of the keys along the way to get there

    def print_dict(v, prefix=''):
        if isinstance(v, dict):
            for k, v2 in v.items():
                p2 = "{}['{}']".format(prefix, k)
                print_dict(v2, p2)
        elif isinstance(v, list):
            for i, v2 in enumerate(v):
                p2 = "{}[{}]".format(prefix, i)
                print_dict(v2, p2)
        else:
            print('{} = {}'.format(prefix, repr(v)))
    

    On your data, it'll print

    data['xml']['config']['portstatus']['status'] = u'good'
    data['xml']['config']['target'] = u'1'
    data['xml']['port'] = u'11'
    

    It's also easy to modify it to track the prefix as a tuple of keys rather than a string if you need it that way.

提交回复
热议问题