推荐学习书目
› 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
ns2250225
V2EX  ›  Python

字典列表怎样合并字典中不同的值

  •  
  •   ns2250225 ·
    ns2250225 · Dec 16, 2017 · 3319 views
    This topic created in 3248 days ago, the information mentioned may be changed or developed.
    有个字典列表是这样:
    l = [
    {"name": "mqx", "url": "www.google.com"},
    {"name": "mqx", "url": "www.baidu.com"},
    {"name": "other", "url": "www.baidu.com"},
    ]
    希望的输出是:
    output = [
    {"name": "mqx", "url": ["www.google.com", "www.baidu.com"]},
    {"name": "other", "url": "www.baidu.com"},
    ]

    请问有什么好的方法吗,希望大神不令赐教
    5 replies  •  2017-12-16 12:22:20 +08:00
    jatesun
    jatesun
    Dec 16, 2017 via iPhone❤️1
    1
    遍历后放入字 list 而不是字符串
    fml87
    fml87
    Dec 16, 2017❤️1
    2
    ```
    from collections import defaultdict
    d = defaultdict(list)
    for i in l:
    d[i['name']].append(i['url'])
    output = [{"name": i[0], "url": i[1]} for i in d.items()]
    ```
    ns2250225
    ns2250225
    OP
    Dec 16, 2017
    3
    @fml87 感谢大神!
    imn1
    imn1
    Dec 16, 2017
    4
    pandas groupby

    如果仅仅是输出,就没必要用 pandas
    不过如果像这种二维变三维,还有后续计算,可以试试 pandas
    codingcrush
    codingcrush
    Dec 16, 2017
    5
    from itertools import groupby
    print([{k: [item["url"] for item in v]} for k, v in groupby(l, key=lambda item: item["name"])])
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   732 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 22:52 · PVG 06:52 · LAX 14:52 · JFK 17:52
    ♥ Do have faith in what you're doing.