The built-in Dictionaries are not ordered collections in the sense that you don't access the values by indexed positions (i.e. 1st, 2nd, etc).
Instead, you access them by keys (e.g. test['hey']
, test['hi']
, etc.). For example:
>>> test = { 'hey':1, 'hi':2, 'hello':3 }
>>> test[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
>>> test['hi']
2
You should look at the Python docs on using dictionaries.
If you want to access elements by position (i.e. an index), then you should consider using a list or a tuple instead.
You might want to look at the OrderedDict
class docs instead if you wish to preserve order while still using a dictionary.
Quoting from the docs:
An OrderedDict is a dict that remembers the order that keys
were first inserted. If a new entry overwrites an existing entry, the
original insertion position is left unchanged. Deleting an entry and
reinserting it will move it to the end.
See idjaw's post for a good example on using the OrderedDict
.