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

字典合并问题请教

  •  
  •   helijia21 · 2019-05-07 10:15:06 +08:00 · 1656 次点击
    这是一个创建于 1808 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有以下 4 个字典

    dict1={'status':'on', 'location':'a'}
    dict2={'status':'on', 'location':'b'}
    dict3={'status':'off', 'location':'c'}
    dict4={'status':'off', 'location':'d'}
    

    有没有什么办法快速得到

    result = {'on':['a','b'], 'off':['c','d']}
    
    6 条回复    2019-05-07 22:34:56 +08:00
    maichael
        1
    maichael  
       2019-05-07 10:20:04 +08:00   ❤️ 1
    把四个字典放在一个数组里,一次遍历判断就搞定了。
    j0hnj
        2
    j0hnj  
       2019-05-07 10:25:30 +08:00   ❤️ 2
    from collections import defaultdict

    result = defaultdict(set)
    for d in [dict1, dict2, dict3, dict4]:
    result[d['status']].add(d['location'])
    result = {k:list(v) for k,v in result.items()}
    helijia21
        3
    helijia21  
    OP
       2019-05-07 10:27:13 +08:00
    明白了 !!多谢 2 位
    cassidyhere
        4
    cassidyhere  
       2019-05-07 10:28:03 +08:00   ❤️ 2
    from operator import itemgetter
    from itertools import groupby

    rows = [dict1, dict2, dict3, dict4]
    for status, items in groupby(rows, key=itemgetter('status')):
    print(status, [i['location'] for i in items])
    helijia21
        5
    helijia21  
    OP
       2019-05-07 10:32:53 +08:00
    python 还是有很多模块能用的 还是太年轻
    xpresslink
        6
    xpresslink  
       2019-05-07 22:34:56 +08:00
    @helijia21 根本用不着模块啊,就一句的事儿。
    dict1={'status':'on', 'location':'a'}
    dict2={'status':'on', 'location':'b'}
    dict3={'status':'off', 'location':'c'}
    dict4={'status':'off', 'location':'d'}
    dicts = [dict1,dict2,dict3,dict4]
    result = {}
    for d in dicts: result.setdefault(d['status'],[]).append(d['location'])
    print(result)
    # {'on': ['a', 'b'], 'off': ['c', 'd']}
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1219 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 23:25 · PVG 07:25 · LAX 16:25 · JFK 19:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.