Dan Von
Dan Von

Reputation: 83

Reverse keys with values list comprehension also randomizes index, how do I fix this?

I have an original dict:

my_dict = {'key1':''value1',
           'key2':'value2',
           'key3':'value3'}

based on which I generate its reverse keys <-> values, like this:

new_dict = {v: k for k, v in my_dict.iteritems()}

which does swap keys for values, but instead of keeping an "orderly order", it switches indices like this:

new_dict = {'key3':''value3',
           'key2':'value2',
           'key1':'value1'}

It is imperative for me that they stay in the same spots.

I've tried to do collections.OrderedDict() but it doesn't help in the generation of the reversed dict.

How can I do this?

Upvotes: 0

Views: 99

Answers (1)

McGrady
McGrady

Reputation: 11477

You can use Orderdict:

my_dict=OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

for k, v in my_dict.items():
    new_dict.update({v: k})
print(new_dict)

And you will get the value:key OrderedDict:

OrderedDict([('value1', 'key1'), ('value2', 'key2'), ('value3', 'key3')])

In python3.6 dict are ordered(under the CPython implementation).

dict() now uses a “compact” representation pioneered by PyPy. The memory usage of the new dict() is between 20% and 25% smaller compared to Python 3.5. PEP 468 (Preserving the order of **kwargs in a function.) is implemented by this. The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5). (Contributed by INADA Naoki in issue 27350. Idea originally suggested by Raymond Hettinger.)

By the way if you need the order,and you want reverse the key/value why don't you try list of tuples,so you don't need to worry about duplicate keys problem:

[ (k1,v1), (k2,v2) ]

Hope this helps.

Upvotes: 1

Related Questions