Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Dictionary Creation - Python

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!

like image 204
eclipsedlamp Avatar asked Apr 18 '26 22:04

eclipsedlamp


1 Answers

You can use a dict comprehension with zip.

res = {k : dict(zip(years, sale)) for k, sale in zip(company, sales)}
like image 192
Unmitigated Avatar answered Apr 20 '26 13:04

Unmitigated



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!