我正在尝试创建一个通用函数来替换嵌套字典的键中的点。我有一个非泛型函数,可深入3个层次,但是必须有一种方法可以实现这种泛型。任何帮助表示赞赏!到目前为止,我的代码:
output = {'key1': {'key2': 'value2', 'key3': {'key4 with a .': 'value4', 'key5 with a .': 'value5'}}}
def print_dict(d):
new = {}
for key,value in d.items():
new[key.replace(".", "-")] = {}
if isinstance(value, dict):
for key2, value2 in value.items():
new[key][key2] = {}
if isinstance(value2, dict):
for key3, value3 in value2.items():
new[key][key2][key3.replace(".", "-")] = value3
else:
new[key][key2.replace(".", "-")] = value2
else:
new[key] = value
return new
print print_dict(output)
更新:要回答我自己的问题,我使用json提出了一个解决方案object_hooks:
import json
def remove_dots(obj):
for key in obj.keys():
new_key = key.replace(".","-")
if new_key != key:
obj[new_key] = obj[key]
del obj[key]
return obj
output = {'key1': {'key2': 'value2', 'key3': {'key4 with a .': 'value4', 'key5 with a .': 'value5'}}}
new_json = json.loads(json.dumps(output), object_hook=remove_dots)
print new_json
最佳答案
是的,存在更好的方法:
def print_dict(d):
new = {}
for k, v in d.iteritems():
if isinstance(v, dict):
v = print_dict(v)
new[k.replace('.', '-')] = v
return new
(编辑:这是递归的,更多关于Wikipedia。)
关于python - Python递归替换嵌套字典键中的字符?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11700705/