Iterate over nested dictionary

后端 未结 5 1897
孤城傲影
孤城傲影 2020-11-30 02:24

Is there an easy way of iterating over nested dictionary, which may consist of other objects like lists, tuples, then again dictionaries so that iteration covers all the ele

5条回答
  •  天命终不由人
    2020-11-30 03:24

    A generator version of Graddy's recurse() answer above that should not explode on strings, and also gives you the compound key (cookie crumb trail?) showing how you arrived at a certain value:

    def recurse(d, keys=()):
        if type(d) == dict:
             for k in d:
                for rv in recurse(d[k], keys + (k, )):
                    yield rv
        else:
            yield (keys, d)
    
    for compound_key, val in recurse(eg_dict):
        print '{}: {}'.format(compound_key, val)
    

    produces output (using the example dictionary provided in the question):

    ('key_1',): value_1
    ('key_2', 'key_21'): [(2100, 2101), (2110, 2111)]
    ('key_2', 'key_22'): ['l1', 'l2']
    ('key_2', 'key_23', 'key_231'): v
    ('key_2', 'key_24', 'key_241'): 502
    ('key_2', 'key_24', 'key_243', 'key_2433'): [(11451, 0), (11452, 0)]
    ('key_2', 'key_24', 'key_243', 'key_2432'): 504
    ('key_2', 'key_24', 'key_243', 'key_2431'): [0, 0]
    ('key_2', 'key_24', 'key_242'): [(5, 0), (7, 0)]
    ('key_2', 'key_24', 'key_244', 'key_2441'): ['ll1', 'll2']
    

    In Python 3 the second yield loop should be replaceable with yield from. This generator could be made more general by replacing the type(d) == dict test with isinstance(d, collections.Mapping), using the Mapping ABC from the collections module.

提交回复
热议问题