展平python中每个键的值

Tel*_*uar 3 python dictionary flatten python-2.7

我有一个这样的字典:

migration_dict = {'30005': ['key42750','key43119', 'key44103', ['key333'],
['key444'], ['keyxx']], '30003': ['key43220', 'key42244','key42230',
['keyzz'], ['kehh']]}
Run Code Online (Sandbox Code Playgroud)

我怎样才能压平每个键的值以便得到类似的东西:

migration_dict = {'30005': ['key42750','key43119', 'key44103', 'key333',
'key444', 'keyxx'], '30003': ['key43220', 'key42244','key42230',
'keyzz', 'kehh']}
Run Code Online (Sandbox Code Playgroud)

Mos*_*oye 9

您可以编写递归函数来展平值列表,并在字典理解中使用它来构建新字典:

def flatten(lst):
   for x in lst:
      if isinstance(x, list):
         for y in flatten(x): # yield from flatten(...) in Python 3
            yield y           #
      else:
         yield x

migration_dict = {k: list(flatten(v)) for k, v in dct.items()}
print(migration_dict)
# {'30005': ['key42750', 'key43119', 'key44103', 'key333', 'key444', 'keyxx'], '30003': ['key43220', 'key42244', 'key42230', 'keyzz', 'kehh']}
Run Code Online (Sandbox Code Playgroud)

它处理dict值列表中的任何嵌套深度.

  • 就在这里,如果任何列表中有自己的引用,这将永远运行;)(+1 ofc) (4认同)