Home > Software design >  Nested Dictionary Creation - Python
Nested Dictionary Creation - Python

Time:01-19

I have a dictionary setup like this:

company = {'Honda': {}
 ,'Toyota':{}
 ,'Ford':{}
}

I have a list containing data like this:

years = ['Year 1', 'Year 2', 'Year 3']

Finally, I also have a list of lists containing data like this:

sales = [[55,9,90],[44,22,67],[83,13,91]]

I am trying to achieve a final result that looks like this:

{'Honda': {'Year 1':55,'Year 2':9,'Year 3':90}
 ,'Toyota':{'Year 1':44,'Year 2':22,'Year 3':67}
 ,'Ford':{'Year 1':83,'Year 2':13,'Year 3':91}
}

I can access the sub-list if sales like this:

for i in sales:
    for j in i:
        #this would give me a flat list of all sales

I can't seem to wrap my head around constructing the final dictionary that would tie everything together.

Any help is appreciated!

CodePudding user response:

You can use a dict comprehension with zip.

res = {k : dict(zip(years, sale)) for k, sale in zip(company, sales)}

CodePudding user response:

You can use zip to pair corresponding information together. First, zip the brand names with the values in sales. Next, zip years with a particular brand's sales numbers.

company = {brand: dict(zip(years, sales_nums)) 
          for brand, sales_nums in zip(["Honda", "Toyota", "Ford"], sales)}

CodePudding user response:

You can use zip and a double for-loop to zip all 3 lists. Here you are:

final_dict = {}
    for i, (name, sub_dict) in enumerate(company.items()):
        for year, sale in zip(years, sales[i]):
            sub_dict[year] = sale
        final_dict[name] = sub_dict
  • Related