while循环不循环并存储在字典中

While loop not looping and storing in dictionary

每次它都会 return 从输入中输入最后一个项目。我是编码的新手,python,如果这是一个愚蠢的问题,我深表歉意。

cars = {}

while True:
   models = input('Please enter car model name: ')
   colors = input('Please enter car color: ')
   cars[models] = colors
   another = input('Do you want to register another car? (y/n): ')
   if another == 'y':
       continue
   else:
       break

print(cars)

它returns:

Please enter car model name: bmw
Please enter car color: red
Do you want to register another car? (y/n): y
Please enter car model name: bmw
Please enter car color: blue
Do you want to register another car? (y/n): y
Please enter car model name: merc
Please enter car color: black
Do you want to register another car? (y/n): n
{'bmw': 'blue', 'merc': 'black'}

它没有 return {'bmw':'red'}

cars = {}
def inputcars():
    models = input('Please enter car model name: ')
    colors = input('Please enter car color: ')
    cars[models] = colors
    another = input('Do you want to register another car? (y/n): ')
    if another == 'y':
        inputcars()


inputcars()
print(cars)

Please enter car model name: ford
Please enter car color: red
Do you want to register another car? (y/n): y
Please enter car model name: subaru
Please enter car color: blue
Do you want to register another car? (y/n): n
{'ford': 'red', 'subaru': 'blue'}

如果您多次输入同一个模型,该模型之前在字典中的颜色将被覆盖。那是因为字典只会为给定的键保存一个值。

尝试提供不同的模型,您将有多个 key/value 对。

Please enter car model name: ford
Please enter car color: blue
Do you want to register another car? (y/n): y
Please enter car model name: chevy
Please enter car color: red
Do you want to register another car? (y/n): n
{'ford': 'blue', 'chevy': 'red'}

我猜你想要的是为每个提供的模型存储多种颜色?

在这种情况下,请考虑使用列表追加,而不是赋值。

from collections import defaultdict

cars = defaultdict(list)

while True:
   model = input('Please enter car model name: ')
   color = input('Please enter car color: ')
   cars[model].append(color)

   another = input('Do you want to register another car? (y/n): ')
   if another != 'y':
      break

print(cars)

如果您想存储“型号、颜色”集合列表,请使用列表而不是字典,因为字典只能为同一键存储一个(最新)值。

cars = []

while True:
   model = input('Please enter car model name: ')
   color = input('Please enter car color: ')
   cars.append([model, color])

   another = input('Do you want to register another car? (y/n): ')
   if another != 'y':
      break

print(cars)

如果您将其中一种变体与某种结构组合(例如 NamedTuple or Dataclasses,您可以得到更多具有命名属性的结构化列表