How to iterate through a Python dictionary in reverse order?
Published on Aug. 22, 2023, 12:17 p.m.
To iterate through a Python dictionary in reverse order, you can use the sorted()
function along with the reverse=True
argument to sort the dictionary keys in reverse order. Here’s an example:
my_dict = {'A': 3, 'B': 4, 'H': 1, 'K': -2, 'T': 0}
for key in sorted(my_dict.keys(), reverse=True):
value = my_dict[key]
print(key, value)
This will print the keys and values of the dictionary in reverse order of keys.
Alternatively, you can use the reversed()
function along with the items()
method of the dictionary to iterate over the key-value pairs in reverse order. Here’s an example:
my_dict = {'A': 3, 'B': 4, 'H': 1, 'K': -2, 'T': 0}
for key, value in reversed(my_dict.items()):
print(key, value)
This will also print the keys and values of the dictionary in reverse order of keys, but does not sort the keys explicitly. Note that the reversed()
function returns a reverse iterator for the given iterable, so it can be used with any iterable, not just dictionaries.