数据字段映射

问题描述 投票:0回答:4

我想映射两本词典。

这些是我的第一本字典中的键和值:

first = {
    "Name": " John Doe", 
    "Gender": "Male", 
    "Phone": "01 9672 0321",
    "Occupation": "Engineer",  
}

第二词典:

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 新手,我很困惑如何做到这一点。

python dictionary key mapping key-value-store
4个回答
0
投票
>>> 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'}

0
投票

由于您的数据有点奇怪,因此必须完成一些硬编码(您在第二个字典中有“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]

0
投票

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]

0
投票

如果您正在寻找一种简单有效的方法来在字典或对象之间映射数据字段,我强烈推荐 field-mapper https://pypi.org/project/field-mapper/ 包。

pip 安装字段映射器

© www.soinside.com 2019 - 2024. All rights reserved.