合并具有相同键的两个字典列表:
问题描述:
好的排列, 我想合并两个字典列表,如果它们具有相同的键:值。它就像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
这将很高兴在这里得到一些帮助。提前致谢。
答
你不想做tbl1[element1]
,假设tbl1
是一个字典列表。 element1
应该已经是你想要的字典,所以只需要element1.copy()
。索引编号tbl2
相同。
+0
你是对的,谢谢你的提示! –
答
鉴于所有的按键都只是字符串,你可以这样做:
>>> [dict(a, **b) for a in series_characters for b in series if a['s_id'] == b['s_id']]
[{'c_id': 'ww', 's_id': 'bb', 'title': 'Breaking Bad'},
{'c_id': 'sw', 's_id': 'bb', 'title': 'Breaking Bad'},
{'c_id': 'sg', 's_id': 'bb', 'title': 'Breaking Bad'},
{'c_id': 'sg', 's_id': 'bcs', 'title': 'Better Call Saul'}]
答
# your code goes here
def joinTable(tbl1, tbl2):
op = []
if len(tbl1) > 0 and len(tbl2) > 0:
keys = set(tbl1[0].keys()).intersection(tbl2[0].keys())
opkeys = set(tbl1[0].keys()).union(tbl2[0].keys())
for row1 in tbl1:
key1 = set(row1.keys())
for row2 in tbl2:
key2 = set(row2.keys())
assert key1.intersection(key2) == keys
assert key1.union(key2) == opkeys
match = True
for key in keys:
match = row1[ key] == row2[key]
if match:
d = dict()
for key in opkeys:
d[ key ] = row1[ key ] if key in row1 else row2[key]
op.append(d)
return op
print joinTable([{'s_id': 'bb', 'title': 'Breaking Bad'},{'s_id': 'bcs', 'title': 'Better Call Saul'}],[
{'c_id': 'ww', 's_id': 'bb'},{'c_id': 'sw', 's_id': 'bb'}, {'c_id': 'sg', 's_id': 'bb'},{'c_id': 'sg', 's_id': 'bcs'}])
它实现SQL的连接算法。类似于https://blogs.msdn.microsoft.com/craigfr/2006/08/03/merge-join/。
您可以进一步扩展它以像特定的键和限制值一样。
in series_charachter for s_id bb,c_id是ww,sw,sg那么为什么它只与sg合并而不是其他的? – harshil9968
@ harshil9968好点,还应该注意,如果有多于一个的常用键,例如在SQL中,tbl1.name = tbl2.name和tbl1.id = tbl2.id。 –