GregMaddux
GregMaddux

Reputation: 87

How to reverse values in a dictionary or list?

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]?

Upvotes: 2

Views: 182

Answers (2)

Anshul Goyal
Anshul Goyal

Reputation: 76887

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]

Upvotes: 12

A.J. Uppal
A.J. Uppal

Reputation: 19264

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

Upvotes: 0

Related Questions