def flatten_dict(d, parent_key='', sep='_'):
"""Flattens a nested dictionary.
:param d: A nested dictionary
:type d: dict or MutableMapping
:param str parent_key: The parent's key. This is a value for tail recursion, so don't set it yourself.
:param str sep: The separator used between dictionary levels
.. seealso:: http://stackoverflow.com/a/6027615
"""
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, (dict, MutableMapping)):
items.extend(flatten_dict(v, new_key, sep=sep).items())
elif isinstance(v, (set, list)):
items.append((new_key, ','.join(v)))
else:
items.append((new_key, v))
return dict(items)
评论列表
文章目录