Loop through all nested dictionary values?

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

    I find this approach a bit more flexible, here you just providing generator function that emits key, value pairs and can be easily extended to also iterate over lists.

    def traverse(value, key=None):
        if isinstance(value, dict):
            for k, v in value.items():
                yield from traverse(v, k)
        else:
            yield key, value
    

    Then you can write your own myprint function, then would print those key value pairs.

    def myprint(d):
        for k, v in traverse(d):
            print(f"{k} : {v}")
    

    A test:

    myprint({
        'xml': {
            'config': {
                'portstatus': {
                    'status': 'good',
                },
                'target': '1',
            },
            'port': '11',
        },
    })
    

    Output:

    status : good
    target : 1
    port : 11
    

    I tested this on Python 3.6.

提交回复
热议问题