I have a dictionary {a:1,b:2,c:3}
.
How can I print in reverse order:
c 3
b 2
a 1
Assuming python 3.6+, for which insertion order in dictionaries is maintained ( guaranteed for python 3.7+ ), you can use reversed
:
d = {'a':1, 'b':2, 'c':3}
out = dict(reversed(d.items()))
# or
out = {k: d[k] for k in reversed(d)}
Output:
{'c': 3, 'b': 2, 'a': 1}
If you want to print
:
for k, v in reversed(d.items()):
print(k, v)
Or:
for k in reversed(d):
print(k, d[k])
Output:
c 3
b 2
a 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.