dict.keys() and dict.values() are always the same order, is it?
gallium.arsenide at gmail.com
Tue Apr 20 08:47:06 CEST 2010
On Apr 20, 1:23 am, Cameron Simpson <c... at zip.com.au> wrote:
> On 19Apr2010 21:31, alex23 <wuwe... at gmail.com> wrote:
> | Cameron Simpson <c... at zip.com.au> wrote:
> | > If items(), keys(), values(), iteritems(), iterkeys(), and
> | > itervalues() are called with no intervening modifications to the
> | > dictionary, the lists will directly correspond. This allows the
> | > creation of (value, key) pairs using zip(): pairs = zip(d.values(),
> | > d.keys()).
> | I stand corrected. Thanks Cameron.
> Oh, I was all ready to say what you said, but decided to check the docs
> myself first:-)
I am not too comfortable relying on it. It feels fragile and
"implementationy" to me, as I'm sure it does to many people (such as
everyone in this thread so far! ;) I do trust the docs on this issue,
but every so often I forget that I read this bit of the docs, and am
once again left with an insecure feeling about it. All in all, the
alternative idiom for flipping keys and values (provided in the docs a
couple of sentences down from your quote) is short enough for my
taste, easy enough for me to read, and never makes me wonder if I
should check the docs just to be sure:
pairs = [(v, k) for (k, v) in d.iteritems()]
Personally, I have never encountered a situation where I thought
"hmm... if only I could rely on pairwise ordering, that would make my
code so much simpler!" I'm sure that's partly because I don't code
enough, but I think it's also due to dictionaries just being pretty
easy to use even without implicitly synchronized pairs.
More information about the Python-list