[Tutor] minor display issue with python dictionaries
Amit Saha
amitsaha.in at gmail.com
Sun Nov 24 22:34:58 CET 2013
On Mon, Nov 25, 2013 at 2:55 AM, Joel Goldstick
<joel.goldstick at gmail.com> wrote:
> On Sun, Nov 24, 2013 at 11:03 AM, Reuben <reuben.dlink at gmail.com> wrote:
>> Hi,
>>
>> ##########################################
>>>>>
>>>>> new_dict = {'a':10, 'b' :20, 'c': 30,'d' : 40}
>>>>>
>>>>>
>>>>> print new_dict
>> {'a': 10, 'c': 30, 'b': 20, 'd': 40}
>>>>>
>>
>>
>> #########################################
>>
>>
>> From the above output, I see key 'c' is at third position during input, but
>> while displaying the output it is displayed at second position
>>
>> Although, I dont see any impact of it since we mainly refer to dictionary
>> values only using "keys" -- but just for curiosity why is this position
>> change?
>>
>> Regards,
>> Reuben
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
> The key is the way to the value. Depending on the implementation,
> python might find the value by different algorithms. Sometimes people
> call dictionaries 'hashes', which I believe refers to a method of
> indexing that does some algorithm on the key to get the value
> location. This is for speed and for space savings in memory.
>
> So, sometimes you might see a dictionary displayed in the order you
> entered it, but sometimes not.
And if order is important, you should look at using OrderedDict [1].
See here [2] for examples.
[1] http://docs.python.org/2/library/collections.html#collections.OrderedDict
[2] http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes
Best,
Amit.
--
http://echorand.me
More information about the Tutor
mailing list