# [Tutor] Re: Calendar question

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Tue Apr 5 22:47:41 CEST 2005

```John Carmona wrote:

> Kristian you wrote:
>
> ---------------------------------------------------------------------------------------------
>
> This assumes all input as integers; if you want months entered by
> name, you'll have to write a conversion routine (hint: use a dict).
> ---------------------------------------------------------------------------------------------
>
>
> I have been looking for a while about doing a conversion routine (using
> a dictionary??), are you saying that I should convert a string (January,
> February, etc.) into integers. Could you please give me some light (do
> not write the code please but just point me to the right direction if
> you can)

A dictionary is a data structure containing keys and values that defines
a mapping from each key to its corresponding value. You define it like this:

>>> squares = {1: 1, 10: 100, 4: 15, 5: 25}

Or an empty dictionary:

>>> emptydict = {}

Once defined, you can access individual elements via their keys:

>>> print squares[4]
15

This way you can also assign values to existing elements:
>>> squares[4] = 4*4
>>> print squares[4]
16

>>> squares[6] = 16
>>> squares[7] = 49

Python raises a KeyError exception if you try to read an element with a
non-existing key:
>>> print squares[9]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in -toplevel-
print squares[9]
KeyError: 9

I used numbers for the keys and the values, but in fact any Python
object can be used as a value. Any immutable object can be used as a
key; for now, just remember that you can use numbers, strings and tuples
as keys.

So what you could do is create a dictionary with the names of the months
as keys and the corresponding numbers as values and use that dictionary
to convert the names in the numbers.

Try to play a bit with dictionaries in IDLE (or your Python shell of
choice). If anything's not clear, just give a yell.

--
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven

```