[Tutor] dictionary question
Kent Johnson
kent37 at tds.net
Thu Jul 28 19:13:27 CEST 2005
David Driver wrote:
> If I
> create a dictionary with the same keys, will it str the same way?
This behaviour is not guaranteed and I wouldn't depend on it. It can break if any other operations have happened on the dict; for example
>>> d=dict(a=1,b=2,c=23)
>>> str(d)
"{'a': 1, 'c': 23, 'b': 2}"
>>> for i in range(100):
... d[i]=i
...
>>> for i in range(100):
... del d[i]
...
>>> str(d)
"{'c': 23, 'b': 2, 'a': 1}"
The order could also change between Python versions if the internal implementation of dict changes.
How about
>>> str(sorted(d.items()))
"[('a', 1), ('b', 2), ('c', 23)]"
Kent
More information about the Tutor
mailing list