Home > Net >  How can I reverse both keys and values in a dictionary in python?
How can I reverse both keys and values in a dictionary in python?

Time:01-21

I have a dictionary {a:1,b:2,c:3}.

How can I print in reverse order:

c 3
b 2
a 1

CodePudding user response:

Assuming python 3.6 , for which insertion order in dictionaries is maintained (guaranteed for python 3.7 ), you can use reversed:

d = {'a':1, 'b':2, 'c':3}

out = dict(reversed(d.items()))

# or
out = {k: d[k] for k in reversed(d)}

Output:

{'c': 3, 'b': 2, 'a': 1}

If you want to print:

for k, v in reversed(d.items()):
    print(k, v)

Or:

for k in reversed(d):
    print(k, d[k])

Output:

c 3
b 2
a 1

CodePudding user response:

You could also use lambda to sort

d = {'a':1, 'b':2, 'c':3}

sorted_d = dict(sorted(d.items(), key=lambda item: -item[1]))
print(sorted_d)

{'c': 3, 'b': 2, 'a': 1}
  • Related