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

问个 Python 字典转换问题。

  •  
  •   Tianny · 2019-11-20 18:30:34 +08:00 · 2701 次点击
    这是一个创建于 1590 天前的主题,其中的信息可能已经有所发展或是发生改变。
    [{'a': {'b':1, 'c':2}}, {'a': {'d':3, 'e':4}}]
    
    如何转换成下面的结构,也就是不同字典里相同 key 的值,如何将对应的 value 合并,并组成一个新的字典
    
    {'a':{'b':1, 'c':2, 'd':3, 'e':4}}
    

    谢谢大家,求支招

    16 条回复    2019-11-27 13:25:45 +08:00
    lhx2008
        1
    lhx2008  
       2019-11-20 18:37:01 +08:00 via Android
    for 一下不就好了,字典合并有方法
    anonymous256
        2
    anonymous256  
       2019-11-20 18:46:35 +08:00 via Android
    print(your_list[0].update(your_list[1]))
    anonymous256
        3
    anonymous256  
       2019-11-20 18:54:19 +08:00 via Android
    测试了下,不可以这样写,而且 update 是不返回结果
    Tianny
        4
    Tianny  
    OP
       2019-11-20 18:58:10 +08:00
    @lhx2008 dict.update(),如果 key 相同,不是会覆盖 value 吗。我不想要覆盖 value
    Tianny
        5
    Tianny  
    OP
       2019-11-20 18:58:32 +08:00
    @anonymous256 是的。而且 update 会覆盖具有相同 key 的 value
    wuwukai007
        6
    wuwukai007  
       2019-11-20 18:59:17 +08:00
    你是单独的一个 a,还是好多个不同的 键,那要分组了
    ClericPy
        7
    ClericPy  
       2019-11-20 18:59:59 +08:00   ❤️ 1
    cherbim
        8
    cherbim  
       2019-11-20 19:03:41 +08:00
    好像之能 for 循环更新键值
    anonymous256
        9
    anonymous256  
       2019-11-20 19:07:05 +08:00
    l = [{'a': {'b': '1'}, 'b': '2'}, {'a': {'c': '3'}}]

    empty = {}
    for item in l:
    for k, v in item.items():
    if k in empty:
    empty[k].update(v)
    else:
    empty[k] = v
    print(empty)
    输出: {'a': {'b': '1', 'c': '3'}, 'b': '2'}

    大致是这样了, 实际的数据可能比这个复杂一点
    anonymous256
        10
    anonymous256  
       2019-11-20 19:08:34 +08:00
    重发一下
    l = [{'a': {'b': '1'}, 'b': '2'}, {'a': {'c': '3'}}]
    empty = {}

    for item in l:
    ....for k, v in item.items():
    ........if k in empty:
    ............empty[k].update(v)
    ........else:
    ............empty[k] = v
    print(empty)
    输出: {'a': {'b': '1', 'c': '3'}, 'b': '2'}
    wuwukai007
        11
    wuwukai007  
       2019-11-20 19:21:48 +08:00   ❤️ 1
    a=[{'a': {'b':1, 'c':2}}, {'a': {'d':3, 'e':4}},{'b':{'q':5}},{'b':{'z':7}}]
    res = pd.DataFrame(a).T
    res.mask(res.isna(),None,inplace=True)
    dict_1 = {}
    buffer = {}
    for key,value in res.iterrows():
    ----x = [buffer.update(i) for i in value if i is not None]
    ----dict_1[key] = buffer.copy()
    ----buffer.clear()
    dict_1 >>> {'a': {'b': 1, 'c': 2, 'd': 3, 'e': 4}, 'b': {'q': 5, 'z': 7}}
    lhx2008
        12
    lhx2008  
       2019-11-20 19:42:11 +08:00
    @Tianny #4 字典的 key 相同的时候,合并的时候肯定会覆盖呀,要是不想覆盖你在转成 k:[v1,v2]
    andylsr
        13
    andylsr  
       2019-11-20 19:51:45 +08:00 via Android
    用 defaultdict,直接对值 update
    andylsr
        14
    andylsr  
       2019-11-20 20:05:21 +08:00   ❤️ 1
    @andylsr
    In [1]: from collections import defaultdict

    In [2]: result = defaultdict(dict)

    In [3]: items = [{'a': {'b':1, 'c':2}}, {'a': {'d':3, 'e':4}}]

    In [4]: for item in items:
    ...: for k, v in item.items():
    ...: result[k].update(v)
    ...: result
    Out[4]: defaultdict(dict, {'a': {'b': 1, 'c': 2, 'd': 3, 'e': 4}})
    Latin
        15
    Latin  
       2019-11-21 14:22:39 +08:00   ❤️ 1
    ...: lst = [{'a': 123}, {'a': 456},{'b': 789}]
    ...:
    ...: temp = {}
    ...: for _ in lst:
    ...: for k, v in _.items():
    ...: dic.setdefault(k, []).append(v)
    ...:
    ...: print([{k:v} for k, v in dic.items()])
    ...:
    ...:
    ...:
    ...: [{'a': [123, 456]}, {'b': [789]}]
    yucongo
        16
    yucongo  
       2019-11-27 13:25:45 +08:00
    from functools import reduce
    lst = [{'a': {'b':1, 'c':2}}, {'a': {'d':3, 'e':4}}]

    data = reduce(lambda x, y: {**x, **y}, [elm.get('a') for elm in lst])

    {'a': data} #-> {'a': {'b': 1, 'c': 2, 'd': 3, 'e': 4}}
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1486 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 17:19 · PVG 01:19 · LAX 10:19 · JFK 13:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.