我正在嘗試使用 Python dicts 進行一些資料轉換。
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 個值,而不是所有的 ids 值。請問有什么提示嗎?
謝謝
uj5u.com熱心網友回復:
您的代碼幾乎是正確的,您只需要更改一個部分,使其看起來像這樣
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,如果沒有,則回傳一個空串列。然后您附加到該串列并使用更新函式將其放回字典中
uj5u.com熱心網友回復:
您需要遍歷電子郵件串列dict2并從中獲取匹配的 iddict1
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]]
如果您愿意,也可以將其轉換為 dict 理解
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']}
uj5u.com熱心網友回復:
一種方法是使用默認字典,然后用單獨的回圈填充它,如下所示:
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']}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485523.html
標籤:Python python-3.x 列表 字典
上一篇:添加可變數量的變數
