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!

2
  • 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 Commented Jan 18, 2023 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. Commented Jan 18, 2023 at 17:34

3 Answers 3

5

You can use a dict comprehension with zip.

res = {k : dict(zip(years, sale)) for k, sale in zip(company, sales)}
Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.