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

如果对字典列表进行快速的合并

  •  
  •   agentwx · 2019 年 11 月 23 日 · 3965 次点击
    这是一个创建于 2258 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如这样的数据
    [{"id":"abc","name":"x","pf":"1"},{"id":"abc","name":"y","pf":"2"},{"id":"abc","name":"z","pf":"1"}]
    怎么快速的变成
    {"id":"abc","data":[{"name":"x","pf":"1"},{"name":"y","pf":"2"},{"name":"z","pf":"1"}]}

    通过遍历重组没有问题,就是觉得是不是太慢了
    13 条回复    2019-11-28 12:03:23 +08:00
    diggerdu
        1
    diggerdu  
       2019 年 11 月 23 日 via iPhone
    用 pandas 吧
    loliordie
        2
    loliordie  
       2019 年 11 月 23 日
    把单条数据的处理函数拆出来扔给 celery 这样的多线程框架, 如果不是上百 G 这种规模一会就处理完了
    66450146
        3
    66450146  
       2019 年 11 月 23 日   ❤️ 2
    如果对字典列表进行快速的合并,这个合并就会很快
    mskf
        4
    mskf  
       2019 年 11 月 23 日
    对于除了 id 主键之外的字段的处理你是用的 data 字段,但是怎么知道哪些是主键哪些不是,如果有外键需不需要加进 data,如果多余字段只有一个需不需要用 data 数组存储,这些你都必须要明确
    widewing
        5
    widewing  
       2019 年 11 月 23 日 via Android
    头大
    又看到 如何->如果
    就很难受
    imn1
        6
    imn1  
       2019 年 11 月 23 日
    昨天问字典的那个是不是你?
    ClericPy
        7
    ClericPy  
       2019 年 11 月 23 日
    不慢
    agentwx
        8
    agentwx  
    OP
       2019 年 11 月 23 日
    @imn1 哪里的?不是我
    cherbim
        9
    cherbim  
       2019 年 11 月 23 日 via iPhone
    这个昨天有人问过
    yucongo
        10
    yucongo  
       2019 年 11 月 27 日
    lst = [{"id":"abc","name":"x","pf":"1"},{"id":"abc","name":"y","pf":"2"},{"id":"abc","name":"z","pf":"1"}]

    data = [dict(zip([*lst[idx].keys()][1:], [*map(lambda elm: lst[idx].get(elm), [*lst[idx].keys()][1:])])) for idx in range(3)]

    {"id":"abc","data":data} #
    yucongo
        11
    yucongo  
       2019 年 11 月 27 日
    简单一点:

    data = [(lambda x: x.pop('id') * False or x)(elm) for elm in lst]
    {"id":"abc","data":data} #
    caoyouming
        12
    caoyouming  
       2019 年 11 月 28 日
    @yucongo #11 小白有点看不懂这个代码啊,解释一下
    caoyouming
        13
    caoyouming  
       2019 年 11 月 28 日
    @yucongo #11 研究了一下,看懂了。哎,python 之路还很长啊。
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   3147 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:24 · PVG 20:24 · LAX 04:24 · JFK 07:24
    ♥ Do have faith in what you're doing.