将字典转换成字典python 3.7 Windows

时间:2018-08-19 16:40:32

标签: 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'}}

3 个答案:

答案 0 :(得分:0)

之所以发生这种情况,是因为您不断重复使用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}

答案 1 :(得分:0)

您的错误是重新使用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: ')

答案 2 :(得分:0)

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'}}