[Tutor] Dictionary Elements

Don Arnold darnold02@sprynet.com
Wed, 16 Oct 2002 06:43:39 -0500


----- Original Message -----
From: <James.Rocks@equant.com>
To: <tutor@python.org>
Sent: Wednesday, October 16, 2002 5:07 AM
Subject: [Tutor] Dictionary Elements


> Hi,
>
> If I have a dictionary of 6 tuples e.g.
>
> {'LONA18': 'GREEN', 'LONTSATL19': 'GREEN', 'LONTSGLA01': 'GREEN',
'LONA15':
> 'GREEN', 'LONA14': 'GREEN', 'LONA17': 'GREEN'}
>

These aren't really tuples, just key/value pairs.

> ... and I want to read BOTH key and value by numerical reference e.g.
print
> dictionary[1] (I know this is wrong) prints:
>
> 'LONA18'
>
> How do I do it?
>

You _can_ do it by calling the dictionary's items() method, which gives you
a list of key/value pairs:

>>> mydict = {0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> print mydict.items()
[(0, 'zero'), (1, 'one'), (2, 'two'), (3, 'three')]
>>> print mydict.items()[2]
(2, 'two')

But you shouldn't really want to. A dictionary is an unordered collection,
so the value of items()[2] can change as things are added or removed from
the dictionary. If you're just wanting an index to step through the
dictionary, you can do something like this:

>>> for key,item in mydict.items():
   print 'key %s has a value of %s' % (key, item)

key 0 has a value of zero
key 1 has a value of one
key 2 has a value of two
key 3 has a value of three


Hope that helps,
Don