输入多维字典
person = {"male":{"name":"Shawn"}, "female":{"name":"Betty","age":[{"aaaa":123},{"bbbb":234}]},"children":{"name":{"first_name":"李", "last_name":{"old":"明明","now":"铭"}},"age":4}}
方案1
拼接所有层级key
def dict_2dm_full(data_json,upperstr=''):
for key in data_json.keys():
if isinstance(data_json[key], dict):
dict_2dm_full(data_json[key],upperstr+key+"_")
else:
key_list[upperstr+key]=data_json[key]
return key_list
输出
{'male_name': 'Shawn', 'female_name': 'Betty', 'female_age': [{'aaaa': 123}, {'bbbb': 234}], 'children_name_first_name': '李', 'children_name_last_name_old': '明明', 'children_name_last_name_now': '铭', 'children_age': 4}
方案2
重名key拼接上层key
def dict_2dm_full_opt(data_json,upperstr=''):
for key in data_json.keys():
if isinstance(data_json[key], dict):
dict_2dm_full_opt(data_json[key],upperstr+key+"_")
else:
_key = key
if key in key_list:
_key = upperstr+ _key
key_list[_key]=data_json[key]
return key_list
输出
{'name': 'Shawn', 'female_name': 'Betty', 'age': [{'aaaa': 123}, {'bbbb': 234}], 'first_name': '李', 'old': '明明', 'now': '铭', 'children_age': 4}
方案3
重名key覆盖
def dict_2dm_min(data_json):
for key in data_json.keys():
if isinstance(data_json[key], dict):
dict_2dm_min(data_json[key])
else:
key_list[key]=data_json[key]
return key_list
输出
{'name': 'Betty', 'age': 4, 'first_name': '李', 'old': '明明', 'now': '铭'}