【问题标题】:How to merge/concat 2 dicts into a tuple?如何将 2 个字典合并/合并成一个元组?
【发布时间】:2021-05-27 22:45:49
【问题描述】:

我很难找到解决方案:

dict_a = {'deecf4bc': 'my_machine'}

dict_b = {'deecf4bc': 'blade-000'}

dict_ab = {'deecf4bc':'my_machine', ' : ', u'blade-000'}

这是我的 dicts 的印刷品:

for key, value in dict_X():
print(key, ' : ', value)

这些 dict 来自 Nova 或 Ironic 等 Python 库 我想根据第一列从其他 2 人创建一个 dict,但我失败了,我试过这个:

x = dict(a.items() + b.items())

还有更多

有人建议:How do I merge two dictionaries in a single expression in Python (taking union of dictionaries)?

它不起作用,因为它显示与dict_b相同

编辑:当我重写字典时,在我看来,我想要的最终数据形式是一个键和两个值,这可能吗?

谢谢

【问题讨论】:

标签: python python-2.7 dictionary


【解决方案1】:

合并字典:

dict_ab = dict_a | dict_b #Python3.9+

dict_ab = {**dict_a, **dict_b} #Python3.5+

【讨论】:

    【解决方案2】:

    查看您的编辑注释,将 2 dict 的值组合在一起,您可以执行以下操作

    >>> a={i:i*10 for i in range(5)}
    >>> b={i:i*100 for i in range(5)}
    >>> a
    {0: 0, 1: 10, 2: 20, 3: 30, 4: 40}
    >>> b
    {0: 0, 1: 100, 2: 200, 3: 300, 4: 400}
    >>> from collections import defaultdict
    >>> c=defaultdict(list)
    >>> for d in [a,b]:
            for k,v in d.iteritems(): #d.items() in py3+
                c[k].append(v)
    
            
    >>> c
    defaultdict(<class 'list'>, {0: [0, 0], 1: [10, 100], 2: [20, 200], 3: [30, 300], 4: [40, 400]})
    >>> 
    

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 2017-07-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2019-11-11
      • 1970-01-01
      • 2018-10-05
      • 1970-01-01
      相关资源
      最近更新 更多