扁平化Python字典有很多很好的解决方案,但大多数递归方法似乎都会在值是字典时自动向键添加“父键”(不管嵌套的键是否-到目前为止-是唯一的)-就像在this solution中一样。这是一个扁平函数,它会在嵌套时自动将父键添加到键中。
def flatten_dict(item, parent_key='', sep='_'):
final = []
for key, val in item.items():
new_key = parent_key + sep + key if parent_key else key
if isinstance(val, dict):
final.extend(flatten_dict(val, parent_key=new_key).items())
else:
final.append((new_key, val))
return dict(final)
我尝试将一组“已使用的密钥”传递给flatten_dict,但仍然将父密钥添加到密钥中(我假设它们在递归中被多次传递,并被标记为已使用)。如果key不是唯一的,有没有一种方法可以使用递归将parent_key添加到key?
例如:
flatten_dict({'a':1, 'b': {'a': 1, 'c': 1}})
返回:
{'a': 1, 'b_a':1, 'b_c': 1}
但理想情况下我希望:
{'a': 1, 'b_a': 1, 'c': 1} # because 'c' is unique
谢谢你的帮助!
发布于 2019-07-31 02:34:13
我建议使用“累加器”字典作为输入参数,而不是列表。这使得能够有效地查找键是否已经存在。
def flat_dict(d, acc=None, parent_key=None, sep="_"):
out = dict() if acc is None else acc
for k, v in d.items():
if type(v) is dict:
flat_dict(v, out, parent_key=str(k))
else:
if k in out:
k = parent_key + sep + str(k)
out[k] = v
return out
如果所有的键都已经是字符串,那么当然可以删除str
类型转换。
https://stackoverflow.com/questions/57275070
复制相似问题