如何合并两个存放字典的列表?

2016-06-01 13:21:05 +08:00
 petelin

django 查询出来的东西经常是这样子的

In [118]: a
Out[118]: [{'id': 1, 'total': 10}, {'id': 2, 'total': 20}]

In [119]: b
Out[119]: [{'id': 1, 'sum': 10324}, {'id': 2, 'sum': 21230}]

a,b 的长度相同,里面每个字典 id 也都是一样的(可能顺序不同)。 我在想怎么把它们合并起来,变成这个样子

Out[120]: [{'id': 1, 'sum': 10324, 'total': 10}, {'id': 2, 'sum': 21230, 'total': 20}]

没有想出来什么好办法(时间上),只能两层 for 循环 加 if 判断,各位有什么办法吗???

1457 次点击
所在节点    问与答
2 条回复
JackeyGao
2016-06-01 13:55:14 +08:00
```
>>> a = [{'id': 1, 'total': 10}, {'id': 2, 'total': 20}]
>>> b = [{'id': 1, 'sum': 10324}, {'id': 2, 'sum': 21230}]
>>> [ dict(x.items() + y.items()) for x, y in zip(a, b) ]
[{'sum': 10324, 'total': 10, 'id': 1}, {'sum': 21230, 'total': 20, 'id': 2}]
>>>
```
xss
2016-06-01 13:58:33 +08:00
hash_array = {}
for each_item in a+b :
if each_item['id'] not in hash_array :
hash_array[each_item['id']] = {'total':each_item['total']} #或者是 sum,自己判断吧,这里只说意思
else :
hash_array[each_item['id']]['sum'] = each_item['sum']

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/282732

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX