字典进入字典python 3.7窗口

  • 本文关键字:字典 窗口 python python
  • 更新时间 :
  • 英文 :


我如何在下面的程序中得到这个?

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字典,并且由于您从未从中删除任何内容,因此它包含所有以前的汽车信息。

试试这个:

dict_cars = {}
while True:
car_number = input ('Insert car number: ')
if car_number == 'end':
break
car_brand = input ('Insert car brand: ')
car_model = input ('Insert car model: ')
dict_cars[car_number] = {car_brand: car_model}

你的错误是重用attributes字典来表示你期望的空字典。实际上,每个字典都不断引用您已经写入的旧内存位置。解决方法是从代码中排除该字典,而只使用空白字典

dict_cars = {}
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] = {}
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: ')
dict_cars = {}
while True:
car_number=0
car_brand=""
car_model=""
car_number = input ('Insert car number: ')
if car_number=='end':
break
car_brand = input ('Insert car brand: ')
car_model = input ('Insert car model: ')
dict_cars[car_number] ={}
dict_cars[car_number][car_brand] = car_model  
print(dict_cars)

上面的代码为您提供了所需的输出。

{1 : {'Mercedes':'E500'}},{ 2 : {'Ford' : 'Focus'}},{ 3 {'Toyota' : 'Celica'}}

最新更新