3

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!

eclipsedlamp
  • 149
  • 9
  • `company` is a dictionary whereas `sales` is a list. How are you supposed to map the dictionary keys to the list indices? Recent versions of Python have dictionaries ordered according to insertion but depending on that doesn't seem to be the proper thing to do. Your input format doesn't seem to be proper for your problem – Abdul Aziz Barkat Jan 18 '23 at 15:07
  • You are correct, I don't think you could guarantee the proper sales would match to company. This was a toy example. – eclipsedlamp Jan 18 '23 at 17:34

3 Answers3

5

You can use a dict comprehension with zip.

res = {k : dict(zip(years, sale)) for k, sale in zip(company, sales)}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • Would you be able to elaborate on how you approached this problem? I am trying to turn this into for loops but I keep getting stuck. – eclipsedlamp Jan 18 '23 at 17:54
  • 1
    @eclipsedlamp You can do it with a for loop like so: `res = {}` then `for k, sale in zip(company, sales): res[k] = dict(zip(years, sale))` – Unmitigated Jan 18 '23 at 18:30
0

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)}
chepner
  • 497,756
  • 71
  • 530
  • 681
0

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
Skapis9999
  • 402
  • 6
  • 14