我想合并两个ID字段。字典x包含许多不同的ID和每个ID不同的行数。字典y包含多个键值,并且总是比dict x少。合并Python列表按键值分组的字典
x = [{'costgroup': '1', 'POC1': '2', 'post': '5','id': '1'},
{'costgroup': '2', 'POC1': '1', 'post': '4','id': '1'},
{'costgroup': '3', 'POC1': '5', 'post': '2', 'id': '1'},
{'costgroup': '1', 'POC1': '2', 'post': '5','id': '2'},
{'costgroup': '2', 'POC1': '1', 'post': '4','id': '2'},
{'costgroup': '3', 'POC1': '5', 'post': '2', 'id': '2'},
{'costgroup': '3', 'POC1': '5', 'post': '2', 'id': '2'}]
y = [{'id': '1', 'laminate': 'D'},
{ 'id':'2', 'laminate': T'}]
的输出,我想是这样的:
z = [{'costgroup': '1', 'POC1': '2', 'post': '5','id': '1','laminate':'D'},
{'costgroup': '2', 'POC1': '1', 'post': '4','id': '1','laminate': 'D'},
{'costgroup': '3', 'POC1': '5', 'post': '2', 'id': '1','laminate': 'D'},
{'costgroup': '1', 'POC1': '2', 'post': '5','id': '2','laminate': 'T'},
{'costgroup': '2', 'POC1': '1', 'post': '4','id': '2','laminate': 'T'},
{'costgroup': '3', 'POC1': '5', 'post': '2', 'id': '2','laminate': 'T'},
{'costgroup': '3', 'POC1': '5', 'post': '2', 'id': '2','laminate': 'T'}]
这是很容易使用熊猫
dfx = pd.DataFrame(x)
dfy = pd.DataFrame(y)
pd.merge(dfx,dfy, how ='left', left_on = 'id', right_on = 'id')
实现但是,我会这样使用AWS lambda函数应用而且我不想承担大熊猫的开销,并且输出需要是字典。我尝试了下面的代码让我更接近,但后来我不得不添加一些东西来找到ID的不同值并遍历它们。但是,仍然没有我需要的输出。
valuelist = ['1']
def copyf(dictlist, key, valuelist):
return [d for d in dictlist if d[key] in valuelist]
y1 = copyf(y, 'id', valuelist)
x1 = copyf(x, 'id', valuelist)
y1.append(x1)
上面提供了这个输出,这是有趣的,但不是我所需要的。
[{'distance': '2', 'id': '1', 'laminate': 'D'},
[{'POC1': '2', 'costgroup': '1', 'id': '1', 'post': '5'},
{'POC1': '1', 'costgroup': '2', 'id': '1', 'post': '4'},
{'POC1': '5', 'costgroup': '3', 'id': '1', 'post': '2'}]]
'y'中的'ids'是否是唯一的? – schwobaseggl
是的,ids在y中是唯一的 – Erich