【问题标题】:Dictionaries into dictionary python 3.7 windows字典到字典 python 3.7 windows
【发布时间】:2018-08-19 16:40:32
【问题描述】:

我怎样才能在下面的程序中得到这个?:

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

【问题讨论】:

  • 如果您的车号始终采用类似的升序排列,您可能需要考虑使用字典列表而不是字典字典。它使索引更简单

标签: python


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      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'}}
      

      【讨论】:

        猜你喜欢
        • 2019-07-17
        • 2017-09-17
        • 1970-01-01
        • 1970-01-01
        • 2019-05-16
        • 2016-07-11
        • 2012-01-22
        • 2015-10-17
        • 2018-05-10
        相关资源
        最近更新 更多