如何将/concat 2个dict合并到一个元组中?

2024-10-03 23:18:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难找到解决方案:

dict_a = {'deecf4bc': 'my_machine'}

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

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

这是我的口述稿,上面写着:

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

这些dict来自像Nova或Ironic这样的Python库 我想在第一列的基础上创建另外两个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相同

编辑:当我重写dicts时,在我看来,我想要的数据的最终形式类似于一个键和两个值,有可能吗

多谢各位


Tags: keyinforabvaluemyitemsmachine
2条回答

要合并词汇表,请执行以下操作:

dict_ab = dict_a | dict_b #Python3.9+

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

查看编辑注释,要将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]})
>>> 

相关问题 更多 >