Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

a problem with using a function and parameters to create a dictionary

I could use some help with this problem. I need to make a function that creates a dictionary with 4 parameters and a key that increase every entry of this dictionary. So far i have this:

def create_db(temp, rain, humidity, wind):
weather = {}
n = 0
for i in (temp, rain, humidity, wind):
    n = n + 1
    weather[n] = (temp, rain, humidity, wind)
return weather

temp = [1, 5, 3]
rain = [0, 30, 100]
humidity = [30, 50, 65]
wind = [3, 5, 7]
weather = create_db(temp, rain, humidity, wind)
print(weather)

problem with this is that it prints:

{1: (1, 0, 30, 3), 2: (1, 0, 30, 3), 3: (1, 0, 30, 3), 4: (1, 0, 30, 3)}

It only put the first value for the list in all for them.
What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

temp, rain etc are lists. You need to reference the element in each list – i.e.

weather[n] = (temp[n], rain[n], humidity[n], wind[n])

You also don’t mean for i in (temp, rain, humidity, wind) – this will be 4, because there are 4 list variables there. Instead use the length of one of the lists, e.g.:

for n in len(temp):

That way you also don’t need to increment n.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading