在python 3.7 windows中导入字典

2024-09-29 19:36:15 发布

您现在位置: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'}}

Tags: 程序numberinputmodelcarcarsdictmercedes
3条回答

之所以会发生这种情况,是因为您一直在重用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'}}

相关问题 更多 >

    热门问题