无法更新嵌套字典中的单个值



在创建像{'key': {'key': {'key': 'value'}}}这样的字典后,我遇到了试图设置较高深度键值的问题。在更新了其中一个值之后,(其他键的)剩余值的值也被更新。

下面是我的Python代码:
times = ["09:00", "09:30", "10:00", "10:30"]
courts = ["1", "2"]
daytime_dict = dict.fromkeys(times)
i = 0
for time in times:
daytime_dict[times[i]] = dict.fromkeys(["username"])
i += 1
courts_dict = dict.fromkeys(courts)
k = 0
for court in courts:
courts_dict[courts[k]] = daytime_dict
k += 1
day_info = [('name', '09:00', 1), ('name', '09:30', 1)]
for info in day_info:
info_court = str(info[2])
time = info[1]
# Here I am trying to set the value for courts_dict['1']['09:00']["username"] to be 'name', 
# but the value for courts_dict['2']['09:00']["username"] and courts_dict['3']['09:00']["username"] is also set to 'name'
# What am I doing wrong? How can I only update the value for where the court is '1'?
courts_dict[info_court][time]["username"] = info[0] 

I desire to get this:

{'1': {'09:00': {'username': 'name'},
'09:30': {'username': 'name'},
'10:00': {'username': None},
'10:30': {'username': None}},
'2': {'09:00': {'username': None},
'09:30': {'username': None},
'10:00': {'username': None},
'10:30': {'username': None}}

但是我得到了这个:

{'1': {'09:00': {'username': 'name'},
'09:30': {'username': 'name'},
'10:00': {'username': None},
'10:30': {'username': None}},
'2': {'09:00': {'username': 'name'},
'09:30': {'username': 'name'},
'10:00': {'username': None},
'10:30': {'username': None}}

(当我只想更新court_dict['1']的值时,请查看court_dict['2']['09:00']['username']court_dict['2']['09:30']['username']是如何被更新的)

从逻辑上讲,我无法理解为什么当我更新courts_dict时这两个值都更新了(我在最后一行代码中是如何做的),而不仅仅是一个。因为info_court"1",所以我认为只有"username"会被更新。

我做错了什么?

逻辑上,我不明白为什么当我更新courts_dict时这两个值都更新了

对于您正在使用的字典对象,您正在分配相同的对象引用作为值,因此您看到"两个值都被更新了"。您可能希望使用copydeepcopy:

重新编写代码。https://docs.python.org/3/library/copy.html

Python中的赋值语句不复制对象,它们在目标对象和对象之间创建绑定。对于可变或包含可变项的集合,有时需要一个副本,这样可以在不改变另一个副本的情况下改变一个副本。

最新更新