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

时间:2021-04-14 15:01:23

标签: python list dataframe dictionary mapping

我正在尝试清理原始联系信息的数据框。原始数据给出了一个人的头衔,我需要根据头衔来确定资历级别。如果标题与字典键部分匹配,我需要将该键的值附加到新列表中。本质上,我需要遍历列表中的每个标题,看看是否与任何字典键部分匹配,并获取相应的字典值并将该值附加到新列表中。我尝试了多种格式的 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']

1 个答案:

答案 0 :(得分:0)

如果标题中没有钥匙

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)