python - 通过键更改其他键来更新Python中的字典
问题描述
我想使用两个列表作为键创建一个字典
regions = ['A','B','C','D']
subregions = ['north', 'south']
region_dict = dict.fromkeys(regions, dict.fromkeys(subregions))
这会产生我想要正确的字典:
{'A': {'north': None, 'south': None},
'B': {'north': None, 'south': None},
'C': {'north': None, 'south': None},
'D': {'north': None, 'south': None}}
但是,如果我尝试更新此字典中的一个元素,我会看到其他元素也在更新
region_dict['A']['north']=1
>>> {'A': {'north': 1, 'south': None},
'B': {'north': 1, 'south': None},
'C': {'north': 1, 'south': None},
'D': {'north': 1, 'south': None}}
我不确定我在这里做错了什么。如何仅更新此字典中的一个值?
解决方案
dict.fromkeys
当每个键使用的值是可变的时,您不能使用;它使用与每个键的值相同的别名,因此无论您查找哪个键,您都会获得相同的值。与 list 的乘法列表基本相同的问题。一个简单的解决方案是用理解替换外部:dict.fromkeys
dict
region_dict = {region: dict.fromkeys(subregions) for region in regions}
推荐阅读
- react-native - 在多层组件的情况下如何纠正事件传播
- android - Xamarin Forms 如何知道当前何时进行呼叫
- php - PHP if isset $_GET 任何参数,如果它们出现在对脚本的 POST 请求中
- ios - JSQMessagesViewController 获取当前文本
- javascript - 类构造函数的未定义返回——JavaScript
- c# - 如何在 c# 中使 jwt 默认令牌作为外部承载无效或销毁?
- php - 如何将元素添加到过去几天和未来几天(仅限工作日)
- python - 如何在不换行的情况下创建 .csv 文件?
- python - 将包含错误/警告的打印语句写入 Spyder 中的文件
- django - 将列表传递给模板 Django 的问题