简体   繁体   中英

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 ie ('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?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM