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)
您可以编写递归函数来展平值列表,并在字典理解中使用它来构建新字典:
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值列表中的任何嵌套深度.
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |