Search code examples
pythonlistdictionarynested-loops

Nested dictionaries from a loop


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

Solution

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