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...

Ender Look
  • 2,303
  • 2
  • 17
  • 41

3 Answers3

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'}
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
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()}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • 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? – Ender Look May 25 '17 at 20:43
  • Thank you for pointing out the error! This is actually dictionary comprehension. – Ajax1234 May 25 '17 at 20:47
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'
Uriel
  • 15,579
  • 6
  • 25
  • 46