2

I have a dictionary

{1:’one’,2:’two’}

I want to reverse it using a function and became to the following

{‘1:’eno’,2:’owt’ }

How can I do it?

Similarly, if I have a list or tuple like [15,49], how can I convert it to [94,51]?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
GregMaddux
  • 87
  • 1
  • 1
  • 7

2 Answers2

12

You can use a simple dict comprehension, using the fact that string[::-1] reverses a string:

>>> d = {1: "one", 2: "two"}
>>> {x: v[::-1] for x, v in d.items()}
{1: 'eno', 2: 'owt'}

You could also define a function:

def reverse_values(dct):
    for key in dct:
       dct[key] = dct[key][::-1]

Which will alter the values in the same dict.

>>> reverse_values(d)
>>> d
{1: 'eno', 2: 'owt'}

For converting list of type [15,49] to [94, 51], you can try the snippet below (this will work for lists of type [12, 34, 56, 78] to [87, 65, 43, 21] as well):

>>> l = [15,49]
>>> [int(str(x)[::-1]) for x in l[::-1]]
[94, 51]
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • another Q if i have a list or tuple I want to become [15,49] => [94,51] , (15,49) = >(94,51) How could I write the function? – GregMaddux May 01 '15 at 04:30
0

For your question here, use the following:

Given that [::-1] reverses the string, we can convert each number to a string, reverse each item, convert back to an integer, then reverse the entire list:

>>> lst = [15, 49]
>>> [int(str(item)[::-1]) for item in lst][::-1]
[94, 51]
>>> 
Community
  • 1
  • 1
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76