尝试同时交叉映射 2 个词典,Python

Trying to cross map 2 dictionaries together, Python

我正在尝试使用 Python 指令进行一些数据转换。

dict1 = {'email1':'id1', 'email2': 'id2', ..}

dict2 = {'abbreviation': ['email1', 'email2', 'email3', ..], 'abbreviation2': ['email2', 'email3', 'email4', ...], ...}

我想要做的是一个 dict,它的输出是这样的:

result = {'abbreviation': [id1, id2, ...]}

我试过了

needed_ids = dict()
temp_list = list()

for email, id in dict1.items():
    for abbrev, list_of_emails in dict_results.items():
        if email in list_of_emails:
            # Get the abbreviation of the language
            temp_lst.append(id)
            needed_ids[abbrev] = temp_lst

这在临时列表中只给了我 1 个值,而不是所有 ID 值。 有什么提示吗?

谢谢

您需要遍历 dict2 中的电子邮件列表并从 dict1

中获取匹配的 ID
dict1 = {'email1':'id1', 'email2': 'id2'}
dict2 = {'abbreviation': ['email1', 'email2', 'email3'], 'abbreviation2': ['email2', 'email3', 'email4']}

needed_ids = dict()

for abbrev, list_of_emails in dict2.items():
    for email in list_of_emails:
        if email in dict1:
            needed_ids[abbrev] = needed_ids.get(abbrev, []) + [dict1[email]]

如果你愿意,也可以将其转换为字典理解

needed_ids = {abbrev: [dict1[email] for email in list_of_emails if email in dict1]
              for abbrev, list_of_emails in dict2.items()}

输出:

{'abbreviation': ['id1', 'id2'], 'abbreviation2': ['id2']}

你的代码几乎是正确的你只需要改变一部分就可以像这样

needed_ids = dict()

for email, id in dict1.items():
    for abbrev, list_of_emails in dict2.items():
        if email in list_of_emails:
            # Get the abbreviation of the language
            current_ids = needed_ids.get(abbrev,[])
            current_ids.append(id)
            needed_ids.update({abbrev:current_ids})

在这个版本中,您将获得当前缩写的 ID,或者如果有 none 它 returns 一个空列表。然后您附加到该列表并使用更新函数将其放回字典中

一种方法是使用默认词典,然后用单独的循环填充它,如下所示:

dict1 = {'email1': 'id1', 'email2':'id2', 'email3':'id3', 'email4':'id4', 'email5':'id5'}
dict2 = {'abbreviation': ['email1', 'email2', 'email3'], 'abbreviation2': ['email2', 'email3', 'email4', 'email5']}

# first store the keys and values into lists
idx_list, abrev_list = [], []  
for abrev in dict2.keys():
    for email, idx in dict1.items():
        if email in dict2[abrev]:
            abrev_list.append(abrev)
            idx_list.append(idx)

# create a default dictionnary
from collections import defaultdict
result = defaultdict(list)

# fill dictionnary with a different loop
for k, v in zip(abrev_list, idx_list):
    result[k].append(v)

dict(result)

>>> {'abbreviation': ['id1', 'id2', 'id3'],
     'abbreviation2': ['id2', 'id3', 'id4', 'id5']}