我想映射两个字典。
这些是我的第一个字典中的键和值:
first = {
"Name": " John Doe",
"Gender": "Male",
"Phone": "01 9672 0321",
"Occupation": "Engineer",
}
字典2:
second = {
"First_Name": "Name",
"Last_Name": "Name",
"Gender": "Gender",
"Phone": "Phone",
"Occupation": "Occupation",
}
输出应该是:
"FirstName": "John",
"LastName": "Doe",
"Gender": "Male",
"Phone": "01 9672 0321",
"Occupation": "Engineer"
我是Python的新手,我很困惑如何做到这一点。
>>> d1 = { "Name": " John Doe", "Gender": "Male", "Phone": "01 9672 0321", "Occupation": "Engineer",
}
>>> d2 = { "First_Name": "Name", "Last_Name": "Name", "Gender": "Gender", "Phone": "Phone", "Occupation": "Occupation", }
>>> {k: d1[v] for k, v in d2.items()}
{'First_Name': ' John Doe', 'Last_Name': ' John Doe', 'Gender': 'Male', 'Phone': '01 9672 0321', 'Occupation': 'Engineer'}
由于您的数据有点奇怪,必须进行一些硬编码(您在第二个字典中有'First_Name',但想要'FirstName'等…)
John Doe开头有空格(我想这是一个错误…)
下面的代码完全符合你的要求:
data1 = { "Name": "John Doe", "Gender": "Male", "Phone": "01 9672 0321", "Occupation": "Engineer",}
data2 = { "First_Name": "Name", "Last_Name": "Name", "Gender": "Gender", "Phone": "Phone", "Occupation": "Occupation", }
data3 = {}
for key in data2.keys():
if key == 'First_Name':
data3['FirstName'] = data1[data2[key]].split(' ')[0]
elif key == 'Last_Name':
data3['LastName'] = data1[data2[key]].split(' ')[1]
else:
data3[key] = data1[key]
修复coyote的一些代码
for key in b.keys():
if key == 'First_Name':
c['FirstName'] = a[b[key]].split(' ')[1]
elif key == 'Last_Name':
c['LastName'] = a[b[key]].split(' ')[2]
else:
c[key] = a[key]