1

I'm sorry if this is a foolish question or a duplicate - I looked but didn't really find anything on this specific question:

I wrote a little cyphering tool for practise, now I'm working on the deciphering part and wondering, how I can use the dictionary I used as a lookuptable to revert this... I can't access the dictionary's key via its value, right?

So I thought I'd turn it around like this:

for x, y in cyphertable.items():
    DEcyphertable = dict(zip(x, y)) 

But this doesn't seem to work. A: What am I doing wrong? and B: How else could I make each "i" in a string look up the value and replace it with the corresponding key?

Billal Begueradj
  • 17,880
  • 38
  • 105
  • 123
Thilo G
  • 95
  • 5

3 Answers3

0

Using Dict comprehension

reverted_dict = {value: key for key, value in cyphertable.items()}

Using zip

reverted_dict = dict(zip(cyphertable.values(), cyphertable.keys()))
hspandher
  • 14,790
  • 2
  • 28
  • 43
0

You can do that simply by:

new_dict = {v: k for k, v in old_dict.items()}

But, note that you may loose some items if you have duplicated values in old_dict (values become keys and keys are unique in a dict).

Outputs:

>>> old_dict = {'a': 1, 'b': 2}
>>> new_dict = {v: k for k, v in old_dict.items()}
>>> new_dict
{1: 'a', 2: 'b'}

If old_dict contains duplicated values:

>>> old_dict = {'a': 1, 'b': 2, 'c': 1}
>>> new_dict = {v: k for k, v in old_dict.items()}
>>> new_dict
{1: 'c', 2: 'b'}
ettanany
  • 17,505
  • 6
  • 41
  • 60
0

Here it is,

In [38]: a = {'a':1,'b':2,'c':3}

In [39]: {j:i for i,j in a.items()}
Out[39]: {1: 'a', 2: 'b', 3: 'c'}

Or

In [40]: dict(zip(a.values(),a.keys()))
Out[40]: {1: 'a', 2: 'b', 3: 'c'}
Rahul K P
  • 10,793
  • 3
  • 32
  • 47