我有此命令dict od
:
OrderedDict([('and', 1), ('that', 1), ('this', 1), ('of', 1), ('truly', 1), ('something', 1), ('nothing', 1), ('important', 2), ('is', 3)])
我正在尝试以相反的顺序打印此词典的键值对。我尝试过:
for k,v in od.items()[-1:]:
print k,v
它打印:
is 3
但是它仅输出最后一个键值对,即('is',3)
。我希望所有的键值对都按相反的顺序排列:
is 3
important 2
nothing 1
something 1
truly 1
of 1
this 1
that 1
and 1
有办法吗?
答案 0 :(得分:1)
使用reversed
例如:
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)
输出:
is 3
important 2
nothing 1
something 1
truly 1
of 1
this 1
that 1
and 1
答案 1 :(得分:1)
reversed
是最好的选择,但是如果您想保留切片的话:
for k, v in od.items()[::-1]:
print k, v
答案 2 :(得分:0)
这是因为列表切片中存在错误。
for k,v in od.items()[-1:]
从最后一个元素迭代到最后(仅打印最后一个元素)
如果您只想更改代码
for k,v in od.items()[::-1]: # iterate over reverse list using slicing
print(k,v)
答案 3 :(得分: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)])