推荐学习书目
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 · Mar 5, 2017 · 5260 views
    This topic created in 3387 days ago, the information mentioned may be changed or developed.

    For example

    d 合并后变成 new_d

    d = [
     {1: [12, 24]},
     {1: [24, 36]},
     {2: [111,222]}
     ]
    
    new_d = [
     {1: [12, 24, 36]},
     {2: [111, 222]}
     ]
    
    Supplement 1  ·  Mar 5, 2017
    谢谢老哥们,已经解决了
    7 replies    2017-03-05 23:55:29 +08:00
    SuperMild
        1
    SuperMild  
       Mar 5, 2017   ❤️ 1
    既然是列表,貌似一般就是遍历了吧,用 set 来做字典的 value 。最后再遍历一次把 set 转换为列表。
    sagaxu
        2
    sagaxu  
       Mar 5, 2017   ❤️ 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()}
    popbones
        4
    popbones  
       Mar 5, 2017
    [ {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  
       Mar 5, 2017
    new_d = {}
    TJT
        6
    TJT  
       Mar 5, 2017
    另外一种思路,前提是 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  
       Mar 5, 2017
    @sagaxu 厉害了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2701 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 155ms · UTC 05:05 · PVG 13:05 · LAX 22:05 · JFK 01:05
    ♥ Do have faith in what you're doing.