我怎么能在下面的程序中得到这个呢?地址:
dict_cars {1 : {'Mercedes':'E500'}},{ 2 : {'Ford' : 'Focus'}},{ 3 {'Toyota' : 'Celica'}}
我当前的程序不工作,我不知道如何修复它:(
dict_cars = {}
attributes = {}
car_number = input ('Insert car number: ')
car_brand = input ('Insert car brand: ')
car_model = input ('Insert car model: ')
while car_number != 'end':
dict_cars[car_number] = attributes
dict_cars[car_number][car_brand] = car_model
car_number = input ('Insert car number: ')
car_brand = input ('Insert car brand: ')
car_model = input ('Insert car model: ')
我想要的是:
Insert car number: 1
Insert car brand: Mercedes
Insert car model: E500
Insert car number: 2
Insert car brand: Ford
Insert car model: Focus
Insert car number: 3
Insert car brand: Toyota
Insert car model: Celica
Insert car number: end
Insert car brand:
Insert car model:
>>> dict_cars
{'1': {'Mercedes': 'E500', 'Ford': 'Focus', 'Toyota': 'Celica'}, '2'{'Mercedes': 'E500', 'Ford': 'Focus', 'Toyota': 'Celica'}, '3': {'Mercedes':
'E500', 'Ford': 'Focus', 'Toyota': 'Celica'}}
之所以会发生这种情况,是因为您一直在重用
attributes
字典,而且您从未从中删除任何内容,它包含了以前的所有汽车信息。你知道吗请尝试以下操作:
你的错误是重用
attributes
字典来表示你期望的空字典。实际上,每一本字典都在引用您已经写入的旧内存位置。解决方法是从代码中排除该字典,而只使用空白字典上面的代码提供了所需的输出。你知道吗
相关问题 更多 >
编程相关推荐