python - 在 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)
解决方案
在 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.'}
}
推荐阅读
- php - Wordpress 排除特色图片
- spring - JPA 和 Hibernate:计算投影中相关条目的数量
- android - 如何将库发布到 https://jitpack.io
- ant-media-server - 仅当 S3 存储桶公开时才可访问 VoD
- awk - 基于三列的子集文件的awk方法
- ios - 如何在 Swift 中使用 CollectionViewPagingLayout 更改滑动方向
- c# - 相机平移操作开始后光标跟随的对象冻结
- authentication - 如何将性别选择从数据库表(性别)添加到 Blazor 身份默认注册表单?
- javascript - 为什么js不想给safari浏览器加个类?
- c - 启用从 typedef (uint32_t) 到 uint32_t 的隐式转换的警告会导致警告,clang