推荐学习书目
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 · 3055 views
    This topic created in 3069 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
        1
    jatesun  
       Dec 16, 2017 via iPhone   ❤️ 1
    遍历后放入字 list 而不是字符串
    fml87
        2
    fml87  
       Dec 16, 2017   ❤️ 1
    ```
    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
        3
    ns2250225  
    OP
       Dec 16, 2017
    @fml87 感谢大神!
    imn1
        4
    imn1  
       Dec 16, 2017
    pandas groupby

    如果仅仅是输出,就没必要用 pandas
    不过如果像这种二维变三维,还有后续计算,可以试试 pandas
    codingcrush
        5
    codingcrush  
       Dec 16, 2017
    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   ·   Solana   ·   6138 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 53ms · UTC 02:04 · PVG 10:04 · LAX 19:04 · JFK 22:04
    ♥ Do have faith in what you're doing.