迭代嵌套字典

the*_*eta 19 python

是否有一种简单的迭代嵌套字典的方法,嵌套字典可能包含其他对象,如列表,元组,然后是字典,以便迭代涵盖这些其他对象的所有元素?

例如,如果我键入嵌套字典对象的键,我会在Python解释器中列出它.


[edit]这里是示例字典:

{
'key_1': 'value_1',
'key_2': {'key_21': [(2100, 2101), (2110, 2111)],
      'key_22': ['l1', 'l2'],
      'key_23': {'key_231': 'v'},
      'key_24': {'key_241': 502,
             'key_242': [(5, 0), (7, 0)],
             'key_243': {'key_2431': [0, 0],
                 'key_2432': 504,
                 'key_2433': [(11451, 0), (11452, 0)]
                },
             'key_244': {'key_2441': {'key_24411': {'key_244111': 'v_24411',
                                'key_244112': [(5549, 0)]
                               },
                          'key_24412':'v_24412'
                         },
                 'key_2441': ['ll1', 'll2']
                }
            },
     }
}
Run Code Online (Sandbox Code Playgroud)

抱歉不可读,但我尽我所能.

Gra*_*ddy 18

def recurse(d):
  if type(d)==type({}):
    for k in d:
      recurse(d[k])
  else:
    print d
Run Code Online (Sandbox Code Playgroud)

  • @theta:工作正常,可以解释你的问题.如果你想让它循环遍历列表,添加一个`elif isinstance([],(list,tuple)):`然后`for d in d:recurse(v)`. (2认同)

Nei*_*ais 7

recurse()上面Graddy答案的生成器版本不应该在字符串上爆炸,并且还为您提供复合键(cookie crumb trail?),显示您如何到达某个值:

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)
Run Code Online (Sandbox Code Playgroud)

产生输出(使用问题中提供的示例字典):

('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']
Run Code Online (Sandbox Code Playgroud)

在 Python 3 中,第二个 yield 循环应该可以替换为yield from. 通过使用 collections 模块中的 Mapping ABC将type(d) == dicttest替换为isinstance(d, collections.Mapping),可以使这个生成器更加通用。