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