J. Smith
J. Smith

Reputation: 51

Converting month numbers to month name using a dictionary in Python

I'm trying to convert an array of numbers (1-12) to the corresponding Month (January-December), however I have to use a dictionary.

I have my months in the form of an array and I get an error for either "TypeError: only length-1 arrays can be converted to Python scalars" or "TypeError: 'dict' object is not callable"

outfile = ("heathrow_weather.npz")

#find out names of arrays
ph_read= np.load(outfile)
print(ph_read.files)

#assign arrays to a variable
max_temp=ph_read['t_max']

month_no=ph_read['month']

year_no=ph_read['year']

rainfall=ph_read['rainfall']

min_temp=ph_read['t_min']


outfile = open("weather_tables.txt", "w")
outfile.write("Month    Year    Min Temp    Max Temp    Rainfall\n")
outfile.write("                   (°C)         (°C)         (mm)\n")


for t0, t1, t2, t3, t4 in zip(month_no, year_no, max_temp, min_temp, rainfall):

string = str(t0)+"      "+str(t1)+"        "+str(t2)+"          "+str(t3)+"         "+str(t4)+"\n"
outfile.write(string)

outfile.close()

all this code works, so it's just for context. The bit I'm struggling with is next

MonthDict={ 1 : "January",
       2 : "February",
       3 : "March",
       4 : "April",
       5 : "May",
       6 : "June",
       7 : "July",
       8 : "August",
       9 : "September",
       10 : "October",
       11 : "November",
       12 : "December"
}

I've tried using:

month_int=int(month_no)
month=MonthDict(month_int)

But i just get the length-1 error.

I also attempted:

for integer in month_no:
month_no = MonthDict(month_no)

But this produces the "dict object not callable" error

Upvotes: 0

Views: 3095

Answers (2)

AChampion
AChampion

Reputation: 30258

As I pointed out in the comments indexing a dict is with [].
But you can also use datetime module to give you the full month name (locale dependent) without creating your own conversion table, e.g.

In []:
import datetime
year_no, month_no = 2017, 3
d = datetime.datetime(year_no, month_no, 1)
d.strftime('%B')

Out[]:
'March'

Or short form:

In []:
d.strftime('%b')

Out[]:
'Mar'

Upvotes: 0

Chris Applegate
Chris Applegate

Reputation: 762

Try MonthDict[month_int] - to access a dict's values you need to use square brackets, not round ones.

Upvotes: 4

Related Questions