V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
aixia
V2EX  ›  Python

有一个成员是字典的列表,如何把其中 key 相同的字典的 value 合并一下

  •  
  •   aixia · 2017-03-05 14:05:43 +08:00 · 4360 次点击
    这是一个创建于 2599 天前的主题,其中的信息可能已经有所发展或是发生改变。

    For example

    d 合并后变成 new_d

    d = [
     {1: [12, 24]},
     {1: [24, 36]},
     {2: [111,222]}
     ]
    
    new_d = [
     {1: [12, 24, 36]},
     {2: [111, 222]}
     ]
    
    第 1 条附言  ·  2017-03-05 14:54:13 +08:00
    谢谢老哥们,已经解决了
    7 条回复    2017-03-05 23:55:29 +08:00
    SuperMild
        1
    SuperMild  
       2017-03-05 14:23:35 +08:00   ❤️ 1
    既然是列表,貌似一般就是遍历了吧,用 set 来做字典的 value 。最后再遍历一次把 set 转换为列表。
    sagaxu
        2
    sagaxu  
       2017-03-05 14:36:00 +08:00   ❤️ 1
    s = {k: set() for x in d for k,v in x.items()}
    [s[k].update(v) for x in d for k,v in x.items()]
    {k: list(v) for k,v in s.items()}
    freestyle
        3
    freestyle  
       2017-03-05 14:36:42 +08:00   ❤️ 1
    popbones
        4
    popbones  
       2017-03-05 14:52:16 +08:00
    [ {id: val} for (id, val) in [[(new_d, new_d.update({k: new_d.get(k, set()).union(set(v))})) for (k, v) in m.items()] for m in d][0][0][0].items() ]
    popbones
        5
    popbones  
       2017-03-05 14:55:33 +08:00
    new_d = {}
    TJT
        6
    TJT  
       2017-03-05 22:14:14 +08:00
    另外一种思路,前提是 d 得排序好

    from itertools import groupby, chain
    [{k: [x for x, _ in groupby(sorted(chain(*[v[k] for v in g])))]} for k, g in groupby(d, lambda x: list(x.keys())[0])]
    mingyun
        7
    mingyun  
       2017-03-05 23:55:29 +08:00
    @sagaxu 厉害了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   974 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 20:28 · PVG 04:28 · LAX 13:28 · JFK 16:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.