Vignesh
Vignesh

Reputation: 11

Is there a way to print a dictionary in a reverse order?

I have this ordered dict od:

OrderedDict([('and', 1), ('that', 1), ('this', 1), ('of', 1), ('truly', 1), ('something', 1), ('nothing', 1), ('important', 2), ('is', 3)])

I am trying to print the key value pairs of this dictionary in the reverse order. I tried this:

for k,v in od.items()[-1:]:
    print k,v

It prints:

is 3

But it prints only the last key value pair i.e. ('is',3). I want all the key value pairs in the reverse order like:

is 3
important 2
nothing 1
something 1
truly 1
of 1
this 1
that 1
and 1

Is there a way?

Upvotes: 1

Views: 3633

Answers (4)

cph_sto
cph_sto

Reputation: 7587

od = OrderedDict([('and', 1), ('that', 1), ('this', 1), ('of', 1), ('truly', 1), ('something', 1), ('nothing', 1), ('important', 2), ('is', 3)])
od_list=[i for i in od.items()]

#Reverse the list
od_list.reverse()

#Create the reversed ordered List.
od_reversed=OrderedDict(od_list)
print(od_reversed)
    OrderedDict([('is', 3),
             ('important', 2),
             ('nothing', 1),
             ('something', 1),
             ('truly', 1),
             ('of', 1),
             ('this', 1),
             ('that', 1),
             ('and', 1)])

Upvotes: 0

kajarenc
kajarenc

Reputation: 103

It is because you have the error in list slicing.

for k,v in od.items()[-1:] iterates from the last element to the end (prints only the last element)

Understanding slice notation

In case you want just change your code

for k,v in od.items()[::-1]: # iterate over reverse list using slicing
    print(k,v)

Upvotes: 1

iz_
iz_

Reputation: 16603

reversed is the way to go, but if you want to stay with slicing:

for k, v in od.items()[::-1]:
    print k, v

Upvotes: 2

Rakesh
Rakesh

Reputation: 82765

Use reversed

Ex:

from collections import OrderedDict

d = OrderedDict([('and', 1), ('that', 1), ('this', 1), ('of', 1), ('truly', 1), ('something', 1), ('nothing', 1), ('important', 2), ('is', 3)])

for k, v in reversed(d.items()):   #or for k, v in d.items()[::-1]
    print(k, v)

Output:

is 3
important 2
nothing 1
something 1
truly 1
of 1
this 1
that 1
and 1

Upvotes: 3

Related Questions