我有两个dictionaires cursor1和cursor2
列表cursor1=conn.cursor(DictCursor)
query1= "SELECT orderid, create_time FROM order_viw_sgd_00000001 "
rows=cursor1.execute(query1)
cursor2=conn.cursor(DictCursor)
query2= "SELECT orderid, total_price FROM order_viw_sgd_00000001 "
rows=cursor2.execute(query2)
例如:
游标1 = [{orderid:001,create_time:10251200},{orderid:002,create_time:10232032}]
光标2 = [{orderid:002,总价:300},{orderid:003,总价:400}]
预期结果:[{orderid:001,create_time:10251200,总价:300}]
如何使用公共密钥(orderid)将cursor1中的每个字典与cursor2中的相应字典内连接?
我知道我们可以使用"加入"在SQL查询命令中,但运行时间太长,效率不高。有没有python方式这样做?
答案 0 :(得分:0)
你可以使用double for循环:
cursor_1=[
{'orderid':'001', 'create_time':10251200},
{'orderid': '002', 'create_time':10232032}
]
cursor_2=[
{'orderid':'002','total_price':300},
{'orderid':'003','total_price':'400'}
]
for x, dict1 in enumerate(cursor_1):
for y, dict2 in enumerate(cursor_2):
if dict1['orderid'] == dict2['orderid']:
cursor_1[x].update(dict2)
del cursor_2[y]
break
else:
## (for ... else) : If for loop finished normally (without break).
cursor_1.append(dict2)
print (cursor_1)