dictionary method question

Raymond Hettinger python at rcn.com
Tue Apr 23 16:38:04 EDT 2002


"Erik Max Francis" <max at alcyone.com> wrote in message
news:3CC5BB74.9070009 at alcyone.com...
> dsavitsk wrote:
>
> > for some dictionary d is there any relationship between the returns from
> > d.keys() and d.values()?  that is, to get them in some arbitrary but
> > matching order, do i need to loop over d.items() or can i count on a
> > similarity of the above? in small tests this seems to be the case.
>
> I presume they would return values in the same object order, but I
> wouldn't count on it.

Erik is absolutely correct on both counts.

The C source for the .keys() and .values() is identical except for the
structure element returned.  So, if given the SAME dictionary, the two
routines will loop of the dictionary in the same order.   HOWEVER, the
dictionary is not guaranteed to remain the same.  A resize operation will
reorder the keys.  Because resize removes dummy entries for previously
deleted items, the order may change even if  the contents of the dictionary
remain the same.

>The .items method is designed expressly for that
> purpose anyway; you're better off using .items since it's potentially
> faster than zipping the two lists together yourself, and it's clearer
> anyway.

Excellent advice.


Raymond Hettinger






More information about the Python-list mailing list