循环中的嵌套字典
Nested dictionaries from a loop
我在遍历三个列表后创建嵌套字典时遇到问题:
year=[1963,1967]
manufacturer=['Jaguar E-Type','MG MGB Roadster']
mileage=[29382,12357]
目标是得到:
{Classic Car 1:{Car:Jaguar E-Type,Year:1963,Mileage:29382},Classic Car 2:{Car:MG MGB Roadster,Year:1967,Mileage: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
一次迭代多个值(如果所有参数的长度相同)。
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}}
或理解:
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)}
您可以使用 zip()
和 enumerate()
的字典理解来生成所需的 key-value 对:
{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}
}
我在遍历三个列表后创建嵌套字典时遇到问题:
year=[1963,1967]
manufacturer=['Jaguar E-Type','MG MGB Roadster']
mileage=[29382,12357]
目标是得到:
{Classic Car 1:{Car:Jaguar E-Type,Year:1963,Mileage:29382},Classic Car 2:{Car:MG MGB Roadster,Year:1967,Mileage: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
一次迭代多个值(如果所有参数的长度相同)。
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}}
或理解:
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)}
您可以使用 zip()
和 enumerate()
的字典理解来生成所需的 key-value 对:
{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}
}