gpt4 book ai didi

python - 有没有办法以相反的顺序打印字典?

转载 作者:行者123 更新时间:2023-12-01 01:16:24 34 4
gpt4 key购买 nike

我有这个有序字典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

有办法吗?

最佳答案

使用反转

例如:

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

关于python - 有没有办法以相反的顺序打印字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54302616/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com