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

如何将一个字典根据 key 值拆分成多个字典? pytthon

  •  
  •   xuegj1010 · 2018-05-11 17:40:09 +08:00 · 6053 次点击
    这是一个创建于 2169 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在有一个字典 a: a = { '0106': '50', '0117': '35', '0203': '30', '0205': '30', '3302': '45', '3305': '45' } 如何根据 key 值前面的两位数拆分成字典 b: b = { '01': { '0106': '50', '0117': '35', }, '02': { '0203': '30', '0205': '30', }, '33': { '3302': '45', '3305': '45', } }

    请问大神用 python 代码如何优雅的实现?

    10 条回复    2018-05-17 10:25:09 +08:00
    aaronzjw
        1
    aaronzjw  
       2018-05-11 17:44:54 +08:00 via iPhone
    collection defaultdict 了解一下
    alvin666
        2
    alvin666  
       2018-05-11 17:49:31 +08:00 via Android
    b={{}}
    for key,value in a.items():
    b[key[:2][key]]=value
    xpresslink
        3
    xpresslink  
       2018-05-11 17:51:35 +08:00   ❤️ 1
    >>> a = { '0106': '50', '0117': '35', '0203': '30', '0205': '30', '3302': '45', '3305': '45' }
    >>> from itertools import groupby
    >>> {k:dict(g) for k,g in groupby(sorted(a.items(), key=lambda x:x[0]), key=lambda x:x[0][:2])}
    {'01': {'0106': '50', '0117': '35'}, '02': {'0203': '30', '0205': '30'}, '33': {'3302': '45', '3305': '45'}}
    wrq
        4
    wrq  
       2018-05-11 18:02:43 +08:00
    >>> a
    {'0117': '35', '0106': '50', '0205': '30', '0203': '30', '3305': '45', '3302': '45'}
    >>> {k[:2]: {i:j for i, j in a.items() if i.startswith(k[:2])} for k, _ in a.items()}
    {'02': {'0205': '30', '0203': '30'}, '33': {'3305': '45', '3302': '45'}, '01': {'0106': '50', '0117': '35'}}
    nullcc
        5
    nullcc  
       2018-05-11 19:00:34 +08:00
    讲真写出来以后我并不觉得优雅:
    >>> groupby_res = groupby(my_dict, lambda e: e[0:2])
    >>>res = dict([(mini_key, dict([(key, my_dict[key]) for key in my_dict.keys() if key.startswith(mini_key)])) for mini_key, group in groupby_res for key in group])
    >>> print(res)
    >>> {'01': {'0106': '50', '0117': '35'}, '02': {'0203': '30', '0205': '30'}, '33': {'3302': '45', '3305': '45'}}

    个人感觉最好还是写得明确一点,分多步构造也没关系。
    kethylar
        6
    kethylar  
       2018-05-11 19:32:56 +08:00
    from collections import defaultdict
    ret = defaultdict(dict)
    for k,v in a.items():
    ret[k[:2]].update({k:v})
    xuegj1010
        7
    xuegj1010  
    OP
       2018-05-11 20:13:59 +08:00
    @nullcc 能写出来都是大神,至少我自己写不出来
    ericls
        8
    ericls  
       2018-05-11 23:42:13 +08:00
    from itertools import group_by
    b = {k: dict(v) for k, v in groupby(list(a.items()), lambda item: item[0][:2])
    ericls
        9
    ericls  
       2018-05-11 23:43:16 +08:00
    from itertools import group_by
    {k: dict(v) for k, v in groupby(a.items(), lambda item: item[0][:2])}
    seabottom1978
        10
    seabottom1978  
       2018-05-17 10:25:09 +08:00
    result = {}
    for i in a:
    if i[:2] not in result:
    result[i[:2]] = {i : a[i]}
    else:
    result[i[:2]][i] = a[i]
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1217 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:24 · PVG 07:24 · LAX 16:24 · JFK 19:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.