Re: Order of elements in a dict

2005-04-26 Thread Steve Holden
Marcio Rosa da Silva wrote: Hi! In dictionaries, unlinke lists, it doesn't matter the order one inserts the contents, elements are stored using its own rules. Ex: >>> d = {3: 4, 1: 2} >>> d {1: 2, 3: 4} So, my question is: if I use keys() and values() it will give me the keys and values in the

Order of elements in a dict

2005-04-26 Thread Marcio Rosa da Silva
Hi! In dictionaries, unlinke lists, it doesn't matter the order one inserts the contents, elements are stored using its own rules. Ex: >>> d = {3: 4, 1: 2} >>> d {1: 2, 3: 4} So, my question is: if I use keys() and values() it will give me the keys and values in the same order? In other words,

Re: Order of elements in a dict

2005-04-26 Thread Paul McGuire
Here is a brute-force list comprehension that does not depend on preserving order between dict.keys() and dict.values(): dict( [ (a[1],a[0]) for a in d.items() ] ) Or for map/lambda lovers: rev = lambda a: (a[1],a[0]) dict( map( rev, d.items() ) But you still have no control over the order retu

Re: Order of elements in a dict

2005-04-26 Thread Leif K-Brooks
Marcio Rosa da Silva wrote: So, my question is: if I use keys() and values() it will give me the keys and values in the same order? It should work fine with the current implementation of dictionaries, but (AFAIK) it's not guaranteed to work by the mapping protocol. So theoretically, it could bre

Re: Order of elements in a dict

2005-04-26 Thread Marcio Rosa da Silva
Thanks for the help! Marcio -- http://mail.python.org/mailman/listinfo/python-list

Re: Order of elements in a dict

2005-04-26 Thread Fredrik Lundh
Marcio Rosa da Silva wrote: > In dictionaries, unlinke lists, it doesn't matter the order one inserts the > contents, elements are > stored using its own rules. > > Ex: > > >>> d = {3: 4, 1: 2} > >>> d > {1: 2, 3: 4} > > So, my question is: if I use keys() and values() it will give me the keys a

Re: Order of elements in a dict

2005-04-26 Thread Duncan Booth
Marcio Rosa da Silva wrote: > In other words, it is safe to do: > > >>> dd = dict(zip(d.values(),d.keys())) > > to exchange keys and values on a dictionary? See the Library Reference, section 2.3.8 Mapping Types: > Keys and values are listed in an arbitrary order which is non-random, > varies

Re: Order of elements in a dict

2005-04-26 Thread Peter Otten
Marcio Rosa da Silva wrote: > In other words, it is safe to do: > > >>> dd = dict(zip(d.values(),d.keys())) Yes, if the dictionary isn't modified between the invocation of values() and keys(). Quoting http://docs.python.org/lib/typesmapping.html """ Keys and values are listed in an arbitrary o