簡體   English   中英

將值列表部分匹配到字典鍵

[英]Partial Matching a list of values to dictionary keys

我正在嘗試清理 dataframe 的原始聯系信息。 原始數據給出了一個人的頭銜,我需要根據頭銜確定資歷。 如果標題與字典鍵有部分匹配,我需要將 append 該鍵的值添加到新列表中。 本質上,我需要遍歷列表中的每個標題,看看是否存在與任何字典鍵的部分匹配,並將相應的字典值和 append 該值抓取到一個新列表中。 我嘗試了多種格式的 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM