Python Forum

Full Version: Assigning a Variable Help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi - I'm new to Python so this is probably a dumb question

Lets say I have variables months of the year that looks like this
month[temperature,days in month, precipitation]

Jan[25,31,3]
Apr[45,30,4]
Jun[85,30,3.3]
Sep[70,30,3.8]
Dec[35,31,2.8]

My code is to input what month you are working with:

month = input("What month is it? ")

Lets say I enter 'Sep'. How do I assign he September values to the variable month so when I type print(month) it returns:

70,30,3.8

Thanks for any help! Much appreciated!
You should choose appropriate datastructure like dictionary for storing month’s data (not separate variables for each month.
Thanks that helped point me in the right direction.

temp = {'MonthOfYear' : {"Jan" , "Feb" , "Mar"} , 'Temperature' : {"25" , "35" , "45"} , 'Days' : {"31" , "28" , "31"} , 'Precipitation' : {"3" , "4" , "5"} }

month = input("What month is it? ")


for var in temp:
    for value in temp[str(var)]:
        if str(value) == str(month):
            print(str(value))
Now this what I have. If I type 'Feb' , how does that return "Feb,35,28,4"? I think I'm still missing something.
A better datastructure is this
temp = {'Jan' : [25,31,3] , 'Apr' : [45,30,4] , 'Jun' : [85,30,3.3] , 'Sep' : [70,30,3.8], 'Dec':[35,31,2.8] }
 
month = input("What month is it? ")
print(temp[month])
Some further convenience can be added to vmarg code. It makes querying data more readable:

>>> months = {'Jan' : [25,31,3] , 'Apr' : [45,30,4] , 'Jun' : [85,30,3.3] , 'Sep' : [70,30,3.8], 'Dec':[35,31,2.8] }
>>> names = ['temperature', 'days in month', 'precipitation']
>>> for month in months:
...     months[month] = dict(zip(names, months[month]))
...
>>> months
{'Jan': {'temperature': 25, 'days in month': 31, 'precipitation': 3},
 'Apr': {'temperature': 45, 'days in month': 30, 'precipitation': 4},
 'Jun': {'temperature': 85, 'days in month': 30, 'precipitation': 3.3},
 'Sep': {'temperature': 70, 'days in month': 30, 'precipitation': 3.8},
 'Dec': {'temperature': 35, 'days in month': 31, 'precipitation': 2.8}}
>>> monthts['Sep']['temperature']
70
>>> max(months, key=lambda x: months[x]['temperature'])                  # month with maximum temperature
'Jun'
>>> min(months, key=lambda x: months[x]['precipitation'])                # month with minimum precipitation
'Dec'
>>> [month for month in months if 50 <= months[month]['temperature']]    # months where temperature was equal or higher than 50
['Jun', 'Sep']
Thanks so much!!