Last answered:

28 Jul 2022

Posted on:

28 Jul 2022

0

How to solve the question using nested loop?

Hi I tried writing a nested loop instead of using the zip function. But I am getting an error. Can you please help me in finding what am I doing wrong?

companies = ['Python DS', 'PythonSoft', 'Pythazon', 'Pybook']
key_name = ['open', 'high', 'low', 'close']
prices = [[12.87, 13.23, 11.42, 13.10],[23.54,25.76,21.87,22.33],
[98.99,102.34,97.21,100.065],[203.63,207.54,202.43,205.24]]

share_prices = dict()

for i in range(4):
    for j in range(4):
        share_prices[companies[i]][key_name[j]]=prices[i][j]
print(share_prices)

I am getting a key error:

KeyError: 'Python DS'

1 answers ( 0 marked as helpful)
Instructor
Posted on:

28 Jul 2022

0

Hey Nirmal,

Thank you for your question!

Below, I provide an example solution to the problem.
image.png
First, a temporary dictionary is defined, called temp_dict, which serves as the value of each key in the share_prices dictionary. The key of temp_dict is key_name[j] while its value is prices[i][j]. At the end of the first loop, we assign temp_dict as the value of share_prices[companies[i]].

Hope this helps!

Kind regards,
365 Hristina

Submit an answer