4 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
將列表之一轉(zhuǎn)換為字典,然后執(zhí)行查找
前任:
perperson = [
{'id':1, 'firstName':'test','lastName':'testlast'},
{'id':2, 'firstName':'test2','lastName':'testlast2'},
{'id':3, 'firstName':'test3','lastName':'last3'},
]
peremail = [
{'id':1, 'email':'test@test'},
{'id':2, 'email':'test2@test2'},
{'id':3, 'email':'test3@test3'},
]
peremail_t = {i.pop('id'): i for i in peremail} # Easy look-up
comdined = [{**i, **peremail_t[i['id']]} for i in perperson]
print(comdined)
輸出:
[{'email': 'test@test', 'firstName': 'test', 'id': 1, 'lastName': 'testlast'},
{'email': 'test2@test2',
'firstName': 'test2',
'id': 2,
'lastName': 'testlast2'},
{'email': 'test3@test3', 'firstName': 'test3', 'id': 3, 'lastName': 'last3'}]
或就地更新
前任:
for i in perperson:
i.update(peremail_t[i['id']])

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果您正在處理字典列表中的大量類(lèi)似表格的數(shù)據(jù),請(qǐng)考慮使用 Pandas 數(shù)據(jù)框。按 id合并數(shù)據(jù)幀非常簡(jiǎn)單,如果表很大,速度會(huì)更快,并且它為您提供了更多方法來(lái)處理 id 不匹配等潛在問(wèn)題。
import pandas as pd
merged = pd.DataFrame(perperson).merge(pd.DataFrame(peremail), on="id")
merged.to_dict("records")如果您需要將其轉(zhuǎn)換回字典,則可以使用。
如果您不想使用 pandas,這里有一個(gè)生成器,可以合并任意數(shù)量的字典列表,這些字典列表可能未排序并且可能具有不匹配的 id(相當(dāng)于 pandas 中的“外部”合并)。這可能比將列表轉(zhuǎn)換為字典慢,但使用列表盡可能高效。
def join_by_key(key, *lists):
? ? lists = [sorted(L, key=lambda d: d[key]) for L in lists]
? ? while lists:
? ? ? ? min_key = min(L[0][key] for L in lists)
? ? ? ? r = {}
? ? ? ? for L in lists:
? ? ? ? ? ? if L[0][key] == min_key:
? ? ? ? ? ? ? ? r.update(L.pop(0))
? ? ? ? yield r
? ? ? ? lists = [L for L in lists if L]
? ? ? ? ? ??
print(list(join_by_key("id", perperson, peremail)))

TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
考慮到所有字典都有一個(gè)“id”鍵,并且列表按“id”值排序:
def combine_dicts(dict_1, dict_2):
if dict_1['id'] == dict_2['id']:
for k in dict_2:
if k in dict_1:
continue
else:
dict_1.update({k:dict_2[k]})
return dict_1
for dict1, dict2 in zip(perperson, peremail):
combine_dicts(dict1, dict2)

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
這是我的建議,一個(gè)簡(jiǎn)單的循環(huán):
perperson = [{'id':1, 'firstName':'test','lastName':'testlast'},
{'id':2, 'firstName':'test2','lastName':'testlast2'},
{'id':3, 'firstName':'test3','lastName':'last3'},
]
peremail = [
{'id':1, 'email':'test@test'},
{'id':2, 'email':'test2@test2'},
{'id':3, 'email':'test3@test3'},
]
for n,j in zip(perperson,peremail):
n['email']=j['email']
print(perperson)
她是輸出
[{'lastName': 'testlast', 'id': 1, 'firstName': 'test', 'email': 'test@test'}, {'lastName': 'testlast2', 'id': 2, 'firstName': 'test2', 'email': 'test2@test2'}, {'lastName': 'last3', 'id': 3, 'firstName': 'test3', 'email': 'test3@test3'}]
- 4 回答
- 0 關(guān)注
- 187 瀏覽
添加回答
舉報(bào)