newbie: dictionary - howto get key value

Peter Otten __peter__ at web.de
Mon Mar 14 09:01:51 CET 2005


Joal Heagney wrote:

> Does python guarantee that the lists given by phone.values() and
> phone.keys() are in mutual order? Or is it possible that python will
> return the lists in different orders for .values() and .keys()?
 
Yes. Quoted from http://docs.python.org/lib/typesmapping.html:

Keys and values are listed in an arbitrary order which is non-random, varies
across Python implementations, and depends on the dictionary's history of
insertions and deletions. 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(a.values(),
a.keys())". The same relationship holds for the iterkeys() and itervalues()
methods: "pairs = zip(a.itervalues(), a.iterkeys())" provides the same
value for pairs. Another way to create the same list is "pairs = [(v, k)
for (k, v) in a.iteritems()]". 

Peter 




More information about the Python-list mailing list