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
ns2250225
V2EX  ›  Python

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

  •  
  •   ns2250225 ·
    ns2250225 · 2017-12-16 07:56:04 +08:00 · 2591 次点击
    这是一个创建于 2321 天前的主题,其中的信息可能已经有所发展或是发生改变。
    有个字典列表是这样:
    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 条回复    2017-12-16 12:22:20 +08:00
    jatesun
        1
    jatesun  
       2017-12-16 08:31:55 +08:00 via iPhone   ❤️ 1
    遍历后放入字 list 而不是字符串
    fml87
        2
    fml87  
       2017-12-16 09:00:00 +08:00   ❤️ 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
       2017-12-16 09:05:52 +08:00
    @fml87 感谢大神!
    imn1
        4
    imn1  
       2017-12-16 10:42:34 +08:00
    pandas groupby

    如果仅仅是输出,就没必要用 pandas
    不过如果像这种二维变三维,还有后续计算,可以试试 pandas
    codingcrush
        5
    codingcrush  
       2017-12-16 12:22:20 +08:00
    from itertools import groupby
    print([{k: [item["url"] for item in v]} for k, v in groupby(l, key=lambda item: item["name"])])
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5323 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 07:47 · PVG 15:47 · LAX 00:47 · JFK 03:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.