首页 > 解决方案 > 在 Python 中合并字典

问题描述

我在 python 中遇到字典问题。当我打印字典时,它只给我一本字典的输出。为糟糕的问题道歉。作为一个新手,我正在努力学习python。

atom1 = {
    'first_name':'Alfa',
    'last_name':'A.',
    'City':'Osaka'
}
atom2 = {
    'first_name':'Beta',
    'last_name':'B.',
    'City':'kyoto'
}
atom3 = {
    'first_name':'Gama',
    'last_name':'G.',
    'City':'L.A.'
}

p = {
    **atom1,**atom2,**atom3
}
print(p)

标签: pythondictionarymerge

解决方案


在 python 中,字典不能有重复的键。因此,当您调用时,p = { **atom1, **atom2, **atom3}您将值“Alfa”分配给键“first_name”,然后再将“Gama”分配给该键。

这就解释了为什么你的最终字典在你的键前面只有最后一个值。例如 'first_name': 'Gama',因为 'Beta' 和 'Alfa' 已被最后的 'first_name' 替换

我建议你试试这个:(应该按原样工作)

p = {
    'atom1': atom1,
    'atom2': atom2,
    'atom3': atom3
}
>>> print(p)
{
    'atom1': {'first_name': 'Alfa', 'last_name': 'A.', 'City': 'Osaka'}, 
    'atom2': {'first_name': 'Beta', 'last_name': 'B.', 'City': 'kyoto'}, 
    'atom3': {'first_name': 'Gama', 'last_name': 'G.', 'City': 'L.A.'}
}

推荐阅读