Ordering of dict keys & values

Chris Rebert clp2 at rebertia.com
Mon Aug 3 23:25:18 CEST 2009


On Mon, Aug 3, 2009 at 1:47 PM, Wells Oliver<wells at submute.net> wrote:
> I understand that the keys in a dictionary are ordered not randomly but
> something practically close to it, but if I create a SQL query like so:
>
> query = 'INSERT INTO Batting (%s) VALUES(%s)' % (','.join(stats.keys()),
> ','.join(stats.values()))
>
> Can I at least rely on the value being in the same index as its
> corresponding key?

Yes. Per http://docs.python.org/library/stdtypes.html#dict.items :
"""
Note: 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(d.values(), d.keys()).
"""

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list