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
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,
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
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
Thanks for the help!
Marcio
--
http://mail.python.org/mailman/listinfo/python-list
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
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
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