来自循环的嵌套字典



在遍历三个列表后创建嵌套字典时遇到问题:

=年(1963、1967)

manufacturer=['Jaguar E-Type','MG MGB Roadster']

里程=(29382、12357)

目的是得到:

{经典车1:{车:捷豹e型,年份:1963,里程:29382},经典车2:{车:MG MGB Roadster,年份:1967,里程:12357}}

我该怎么做呢?

这是我的代码:

def classiccars():
for car in manufacturer:
classiccar={}
position=manufacturer.index(car)
classiccar["Car"]=car
classiccar["Year"]=year[position]
classiccar["Mileage"]=mileage[position]
classiccar_update={}
classiccar_update[car]=classiccar_update
print(classiccar_update)
classiccars()

您可以对zip()enumerate()使用字典推导来生成所需的键值对:

{f"Classic_Car_{idx}": dict(zip(['Car', 'Year', 'Mileage'], values))
for idx, values in enumerate(zip(manufacturer, year, mileage), start=1)}

这个输出:

{
'Classic_Car_1': {'Car': 'Jaguar E-Type', 'Year': 1963, 'Mileage': 29382},
'Classic_Car_2': {'Car': 'MG MGB Roadster', 'Year': 1967, 'Mileage': 12357}
}

您可以使用zip一次迭代多个值(如果所有参数长度相同)

y = {}
for i, car, yr, miles in zip(range(1, len(year)+1), manufacturer, year, mileage):
y[f"Classic Car {i}"] = {"Car": car, "Year": yr, "Mileage": miles}
>>> y
{'Classic Car 1': {'Car': 'Jaguar E-Type', 'Mileage': 29382, 'Year': 1963},
'Classic Car 2': {'Car': 'MG MGB Roadster', 'Mileage': 12357, 'Year': 1967}}

Or带推导式:

y = {f"Classic Car {i}": {"Car": car, "Year": yr, "Mileage": miles}
for i, car, yr, miles in zip(range(1, len(year)+1), manufacturer, year, mileage)}

相关内容

  • 没有找到相关文章