将值列表部分匹配到字典键

2024-09-29 01:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试图清除原始联系人信息的数据框。原始数据给出了一个人的头衔,根据头衔我需要确定资历级别。如果标题与dictionary键部分匹配,我需要将该键的值附加到一个新列表中。本质上,我需要遍历列表中的每个标题,查看是否有与任何字典键的部分匹配,并获取相应的字典值,然后将该值附加到新列表中。我尝试了多种形式的for循环和列表理解,但没有成功

下面是列表和命令的示例:

title = ['CEO', 'CFO', 'Financial Analyst', 'Associate', 'Tax Manager', 'Audit Manager']
seniority_dict = {'CEO':'Exec', 'CFO':'Exec', 'Manager':'Manager', 'Analyst':'Associate', 'Associate':'Associate'}

下面是上面列表中相应值的资历

seniority = ['Exec', 'Exec', 'Associate', 'Associate', 'Manager', 'Manager']

Tags: 数据信息标题列表字典manager联系人associate
1条回答
网友
1楼 · 发布于 2024-09-29 01:27:05

如果你没有钥匙不在标题里

title = ['Software Engineer', 'CEO', 'CFO', 'Financial Analyst', 'QA Engineer', 'Associate', 'Tax Manager', 'Audit Manager']
seniority_dict = {'CEO': 'Exec', 'CFO': 'Exec', 'Manager': 'Manager', 'Analyst': 'Associate', 'Associate': 'Associate'}

new_list = []
for t in title:
    found = False
    for key, value in seniority_dict.items():
        if key in t:
            new_list.append(value)
            found = True
            break
    if not found:
        new_list.append('NaN')
print(new_list)

相关问题 更多 >