[Tutor] Using contents of a document to change file names, (was Re: how to extract data only after a certain ...)

Joel Goldstick joel.goldstick at gmail.com
Tue Oct 12 21:15:57 CEST 2010


On Tue, Oct 12, 2010 at 2:46 PM, Josep M. Fontana <josep.m.fontana at gmail.com
> wrote:

>
>
> On Tue, Oct 12, 2010 at 8:37 PM, Joel Goldstick <joel.goldstick at gmail.com>wrote:
>
>>
>>
>> On Tue, Oct 12, 2010 at 1:52 PM, Josep M. Fontana <
>> josep.m.fontana at gmail.com> wrote:
>>
>>> Thanks Chris and Alan,
>>>
>>> OK, I see. Now that I managed to build the dictionary, I did a print to
>>> confirm that indeed the dictionary was created and it had the intended
>>> contents and I was surprised to see that the order of the items in it was
>>> totally changed. So the text file from which the dictionary was created was
>>> sorted in alphabetical order ('A-01,1334', 'A-02,1234',...'I-01,1334'...),
>>> but when I print the dictionary, I get: {'I-02': '1399', 'I-01': '1374',
>>> 'D-09': '1524', 'I-07': '1399' .....}
>>>
>>> I don't think this will be a problem for what I want to do next but I'm
>>> curious to know why the order is all changed in a way that doesn't seem to
>>> be very intuitive.
>>>
>>
>> Here is a discussion of how to iterate over a dictionary in sorted order:
>>
>>
>> http://stackoverflow.com/questions/364519/in-python-how-to-i-iterate-over-a-dictionary-in-sorted-order
>>
>
>
> Thanks very much, Joel, for your quick response. This information might be
> useful but my question was really more out of curiosity to know how Python
> works. I don't understand why a dictionary that was created by iterating
> over a list that was sorted turns out to be unsorted. I would not have been
> surprised if the order was reversed, but the order that I got makes no sense
> to me. What is the logic of the order in which the items in this dictionary
> are arranged?
>
> JM
>
>
>>
>>
Well, dictionaries use keys which are stored in hash tables.  A dictionary
is a mapping.  It doesn't require an order.  It just requires that given a
key, it will return a value.  While I don't know enough about this to be
instructive, it makes looking up values faster.  When the dictionary is
retrieved, its order depends on the hashed values rather than the keys
themself.  If you play around with a dictionary, adding new key-value pairs,
then displaying the dict, you might find that the order changes in no
particular way.  Here is a wikipedia article.
http://en.wikipedia.org/wiki/Hash_table

A list, on the other hand IS ordered (its a squence), and so when you add or
remove values from a list, the order is maintained.

-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20101012/7e18e2eb/attachment-0001.html>


More information about the Tutor mailing list