3

This question could sound something stange, but normally you can get values by the key, e.g:

>>> mydict = {'a':1,'b':2,'c':3} >>> mydict['a'] 1 >>> mydict['b'] 2 >>> mydict['c'] 3 

But I need to do:

>>> mydict[1] 'a' >>> mydict[2] 'b' >>> mydict[3] 'c' # In this case, my dictionary have to work like >>> mydict = {1:'a',2:'b',3:'c'} 

In my program my dictionary could be open by the two ways, I mean:

>>> mydict = {'a':1,'b':2,'c':3} # Sometimes I need the value of a letter: >>> mydict['a'] 1 # And somethimes, I need the letter of a value. >>> mydict.REVERSAL[1] a 

I can do something like: (I don't know if this work, I don't test it)

>>> mydict = {'a':1,'b':2,'c':3} >>> mydict['a'] 1 # etc... >>> def reversal(z): ... tmp = {} ... for x,y in z.items(): ... tmp[y] = x ... return tmp >>> mydict = reversal(mydict) >>> mydict[1] a # etc >>> mydict = reversal(mydict) >>> mydict['c'] 3 # etc, etc, etc... 

Is there an easy way to do that?
FIRST: I know about chr() and ord(), my code isn't about letters... this is only and example.
SECOND: In my dictionary there won't be two same values, so there won't be any problems with duplicate keys...

2

3 Answers 3

2

You need something like this,

In [21]: mydict = {'a':1,'b':2,'c':3} In [22]: dict(zip(mydict.values(),mydict.keys())) Out[22]: {1: 'a', 2: 'b', 3: 'c'} 

Or

In [23]: dict(i[::-1] for i in mydict.items()) Out[23]: {1: 'a', 2: 'b', 3: 'c'} 

Or

In [24]: dict(map(lambda x:x[::-1],mydict.items())) Out[24]: {1: 'a', 2: 'b', 3: 'c'} 
Sign up to request clarification or add additional context in comments.

5 Comments

Other answer use {b:a for a, b in mydict.keys()} instead of your code, what is the difference?
The difference is i have used the method that dict will convert list of tuples into a dictionary.
Sorry, I didn't understand. ¿You make a dict >>> tuple, reverse the keys and values, and they tuple >>> dict? ¿Is friendly perfomance?
dict([(1,'a'),(2,'b'),(3,'c')]) this will be the model.
Thanks for your help but I will acept another easier answer (I'll upvote you).
1

To reverse your dictionary, you can use .items():

mydict = {'a':1,'b':2,'c':3} new_dict = {b:a for a, b in mydict.items()} 

2 Comments

Thanks for your one-line code! But your code have an error, change .keys() for .items() fix it. Thank, but one question, is this a list comprehension?
Thank you for pointing out the error! This is actually dictionary comprehension.
1

You can use some dictionary comprehension to switch keys and values:

>>> mydict = {'a': 1, 'b': 2, 'c': 3} >>> reversal = {v: k for k, v in mydict.items()} >>> reversal[1] 'a' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.