深度阅读

How to iterate through a Python dictionary in reverse order?

作者
作者
2023年08月22日
更新时间
10.2 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。