我有两个dict,dict1和dict2,我想用键值对构造新的dict(或操作dict1)(dict2的值:dict1的值[其中dict的键和dict2的键相同]),value键的列表可能是dicts列表(正如您将在输入示例中看到的那样)
输入是
dict1 = {"key1":{"key3":"value1","key2":"value2","key4":{"key5":"value3","key6":{"key7":"value4","key8":{"key9":"value5","key10":"value6","key55":"value7"}},"key11":{"key12":"value8","key13":"value9"},"key14":[{"key15":"value10","key16":"value11","key17":"value12"},{"key15":"value13","key16":"value14","key17":"value15"}]}}}
dict2 = {"key1":"ab","key2":"bc","key3":"cd","key4":"de","key5":"ef","key6":"fg","key7":"gh","key8":"hi","key9":"ij","key10":"jk","key55":"kl","key11":"lm","key12":"mn","key13":"no","key14":"op","key15":"pq","key16":"qr","key17":"qs"}
我的功能是
def walk(dict1, dict2):
output = {}
for key, value in dict1.iteritems():
if isinstance(value, dict):
output[dict2[key]] = walk(value, dict2)
elif isinstance(value, list):
output[dict2[key]] = walk_list(value, dict2)
else:
output[dict2[key]] = value
return output
def walk_list(sublist, dict2):
output = []
for i in sublist:
if isinstance(i, dict):
output = walk(i, dict2)
elif isinstance(value, list):
output = walk_list(i, dict2)
else:
output.append((key, value))
return output
output = walk(dict1, dict2)
output = json.dumps(output)
print output
输出就是
{"ab": {"de": {"lm": {"mn": "value8", "no": "value9"}, "ef": "value3", "fg": {"hi": {"ij": "value5", "jk": "value6", "kl": "value7"}, "gh": "value4"}, "op": {"pq": "value13", "qs": "value15", "qr": "value14"}}, "bc": "value2", "cd": "value1"}}
预期产出是
{"ab":{"cd":"value1","bc":"value2","de":{"ef":"value3","fg":{"gh":"value4","hi":{"ij":"value5","jk":"value6","kl":"value7"}},"lm":{"mn":"value8","no":"value9"},"op":[{"pq":"value10","qr":"value11","qs":"value12"},{"pq":"value13","qr":"value14","qs":"value15"}]}}}
请修复我的代码.