【发布时间】:2017-04-20 05:55:27
【问题描述】:
晚上好, 如果它们具有相同的键:值,我想合并两个字典列表。它就像 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'}
输出应该是包含两个信息的字典列表:
out= [
{'s_id': 'bb', 'title': 'Breaking Bad', 'c_id': 'ww'},
{'s_id': 'bcs', 'title': 'Better Call Saul', 'c_id': 'sg'}]
我尝试过类似的东西,但我认为我的想法太复杂了,代码不起作用:
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
很高兴在这里获得一些帮助。提前致谢。
【问题讨论】:
-
在s_id bb的series_charachter中,c_id是ww ,sw, sg 那为什么只和sg合并而不是其他呢?
-
@harshil9968 好点,还应该注意如果有多个公共密钥,例如在 SQL 中,其中 tbl1.name=tbl2.name 和 tbl1.id=tbl2.id。
标签: python dictionary merge key