Loop through all nested dictionary values?

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

    Here's a modified version of Fred Foo's answer for Python 2. In the original response, only the deepest level of nesting is output. If you output the keys as lists, you can keep the keys for all levels, although to reference them you need to reference a list of lists.

    Here's the function:

    def NestIter(nested):
        for key, value in nested.iteritems():
            if isinstance(value, collections.Mapping):
                for inner_key, inner_value in NestIter(value):
                    yield [key, inner_key], inner_value
            else:
                yield [key],value
    

    To reference the keys:

    for keys, vals in mynested: 
        print(mynested[keys[0]][keys[1][0]][keys[1][1][0]])
    

    for a three-level dictionary.

    You need to know the number of levels before to access multiple keys and the number of levels should be constant (it may be possible to add a small bit of script to check the number of nesting levels when iterating through values, but I haven't yet looked at this).

提交回复
热议问题