[Tutor] iterating data and populating a dictionary

W W srilyk at gmail.com
Thu Aug 7 14:42:37 CEST 2008

On Thu, Aug 7, 2008 at 12:42 AM, Shrutarshi Basu <technorapture at gmail.com>wrote:

> If you're just going to be using numbers as dictionary keys, it might
> be simpler just to use a list structure. Dictionaries don't preserve
> order, so you'd need to write extra code if you ever need to iterate
> over it in order.

It wouldn't be any (or at least much) more difficult than looping over a
list of known/unknown length.

Known length:

for x in range(0, length):
    do something with mydict[x]

Unknown length, dict keys starting at 0:

for x in range(0, len(mydict)):
    do something with mydict[x]

Known length, dict keys starting at 1:

for x in range(1, (len(mydict)+1)):
    do something with mydict[x]

Probably not the most elegant solution, but it does work. I can't really
think of a particular reason it would be useful, though. The main reason a
dict is useful is for key values that won't change, and aren't easily kept
track of (i.e. names). It's a lot more difficult (at least for the
interpreter, as in processor cycles) to find "John Smith" in a list, than to
convert it to a hash value and look it up in a hash table.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080807/a4778a23/attachment.htm>

More information about the Tutor mailing list