Regarding Dictionaries in python
Andy Jewell
andy at wild-flower.co.uk
Tue Apr 22 14:03:24 EDT 2003
On Monday 21 Apr 2003 9:34 pm, Mehta, Anish wrote:
> Hello !
>
> I am having a small query regarding dictionaries in python. From
> Orelly's Programming Python
>
> >>>D= {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4}
> >>>D.items()
>
> [ ('b', 2), ('c', 3), ('d', 4), ('a', 1)]
>
>
> why it is not showing the items in order in which i have inserted.
> Please tell me why it is happing like this.
>
> Thanks in advance.
>
> Regards...
Dictionaries are not ordered entities - check the Tutorial. They use a
hashing algorithm to retrieve items, and as items are added, they are stored
in a 'bucket' that is unique to that item. The order of the buckets cannot
be influenced (it's coded into Python). For details on how hashing
algorithms work, scan google...
Numeric items are always added in ascending order (as far as my little
experiments showed anyway):
>>> d={}
>>> d[1]="one"
>>> d
{1: 'one'}
>>> d[2]="two"
>>> d
{1: 'one', 2: 'two'}
>>> d[3]="three"
>>> d
{1: 'one', 2: 'two', 3: 'three'}
>>> d[4]="four"
>>> d
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
String values are added in a manner appropriate for sequences:
>>> for l in "abcdef":
d[l]=l
print d
{'a': 'a'}
{'a': 'a', 'b': 'b'}
{'a': 'a', 'c': 'c', 'b': 'b'}
{'a': 'a', 'c': 'c', 'b': 'b', 'd': 'd'}
{'a': 'a', 'c': 'c', 'b': 'b', 'e': 'e', 'd': 'd'}
{'a': 'a', 'c': 'c', 'b': 'b', 'e': 'e', 'd': 'd', 'f': 'f'}
{'a': 'a', 'c': 'c', 'b': 'b', 'e': 'e', 'd': 'd', 'g': 'g', 'f': 'f'}
I'd imagine tuples are handled similarly, but I haven't tried them...
Hope that helps.
-andyj
More information about the Python-list
mailing list