V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
petelin
V2EX  ›  问与答

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

  •  
  •   petelin · 2016-06-01 13:21:05 +08:00 · 1429 次点击
    这是一个创建于 2898 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 判断,各位有什么办法吗???

    2 条回复    2016-06-01 13:58:33 +08:00
    JackeyGao
        1
    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
        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']
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1034 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 21:59 · PVG 05:59 · LAX 14:59 · JFK 17:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.