1

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?

Georgy
  • 6,348
  • 7
  • 46
  • 58
Vignesh
  • 11
  • 2

4 Answers4

2

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
Rakesh
  • 75,210
  • 17
  • 57
  • 95
2

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

for k, v in od.items()[::-1]:
    print k, v
iz_
  • 13,337
  • 2
  • 19
  • 37
0

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)
kajarenc
  • 73
  • 4
0
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)])
cph_sto
  • 5,368
  • 6
  • 31
  • 55