Home > Enterprise >  Nested dictionaries from a loop
Nested dictionaries from a loop

Time:04-22

I'm having trouble creating a nested dictionary after looping through three lists:

year=[1963,1967]

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

mileage=[29382,12357]

The aim is to get:

{Classic Car 1:{Car:Jaguar E-Type,Year:1963,Mileage:29382},Classic Car 2:{Car:MG MGB Roadster,Year:1967,Mileage:12357}}

How do I go about it?

This is my code:

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()

CodePudding user response:

You can use a dictionary comprehension with zip() and enumerate() to generate the desired key-value pairs:

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

This outputs:

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

CodePudding user response:

You can use zip to iterate with multiple values at once (If all arguments are of the same length).

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 with a comprehension:

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)}
  • Related