好的排列, 我想合併兩個字典列表,如果它們具有相同的鍵:值。它就像SQL中的連接一樣。我不允許爲這個問題導入任何模塊。合併具有相同鍵的兩個字典列表:
下面的例子:
輸入:
>>> series = [
... {'s_id': 'bb', 'title': 'Breaking Bad'},
... {'s_id': 'bcs', 'title': 'Better Call Saul'}]
>>> series_characters = [
... {'c_id': 'ww', 's_id': 'bb'},
... {'c_id': 'sw', 's_id': 'bb'},
... {'c_id': 'sg', 's_id': 'bb'}
... {'c_id': 'sg', 's_id': 'bcs'}
輸出應類型的字典中既infomration裏面的清單:
out= [
{'s_id': 'bb', 'title': 'Breaking Bad', 'c_id': 'ww'},
{'s_id': 'bcs', 'title': 'Better Call Saul', 'c_id': 'sg'}]
我嘗試財產以後這樣的,但我認爲,我的想法是複雜的,代碼doesen't工作:
def _join(tbl1, tbl2):
"""
Helping function to merge two tables inform of a list
Argurments:
tbl1 (list): list of dict's containung a table
tbl2 (list): list of dict's containung a table
Returns:
back_lst (list): list, containing wanted rows of the table
"""
back_lst = []
for element1 in tbl1:
for element2 in tbl2:
for key in tbl1[element1]:
if tbl1[element1[key]] == tbl2[element2[key]]:
a = tbl1[element1].copy()
a.update(tbl2[element2])
back_lst.append(a)
return back_lst
這將很高興在這裏得到一些幫助。提前致謝。
in series_charachter for s_id bb,c_id是ww,sw,sg那麼爲什麼它只與sg合併而不是其他的? – harshil9968
@ harshil9968好點,還應該注意,如果有多於一個的常用鍵,例如在SQL中,tbl1.name = tbl2.name和tbl1.id = tbl2.id。 –