【问题标题】:Merging Dictionary in Python [duplicate]在Python中合并字典[重复]
【发布时间】:2021-11-05 08:05:25
【问题描述】:

我在 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)

【问题讨论】:

  • 这是设计使然。所有 3 个字典都有相同的键,所以最后一个字典“赢”
  • 你的预期输出是什么?
  • dict 基本上是键和值之间的映射。它假定密钥是唯一的(例如,您只能拥有一个密钥first_name)。在您的情况下,您正在尝试合并 3 个具有相同键的字典。这是做不到的。您的预期输出是什么?
  • 感谢@balderman 的澄清。我现在明白了。我的预期输出假设是所有 3 个字典的集合,例如: first_name: alpha last_name:a city:Osaka first_name: beta last_name:b city:kyoto

标签: python dictionary merge


【解决方案1】:

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

这解释了为什么您的最终 dict 将只有键前面的最后一个值。例如 '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.'}
}

【讨论】:

  • 非常感谢 Alexandre 的建议。成功了!
猜你喜欢
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
相关资源
最近更新 更多