Python反向字典项目顺序 [英] Python reverse dictionary items order

查看:47
本文介绍了Python反向字典项目顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一本字典:

d = {3: 'three', 2: 'two', 1: 'one'}

我想重新排列这本词典的顺序,以便该词典是:

I want to rearrange the order of this dictionary so that the dictionary is:

d = {1: 'one', 2: 'two', 3: 'three'}

我在想类似 reverse()函数的列表,但这没用.预先感谢您的回答!

I was thinking something like the reverse() function for lists, but that did not work. Thanks in advance for your answers!

推荐答案

自python 3.8及更高版本开始,items视图可以反向迭代,因此您可以执行以下操作:

Since Python 3.8 and above, the items view is iterable in reverse, so you can just do:

d = dict(reversed(d.items()))

在3.7和3.6上,他们还没有实现 dict dict 视图上的 __ reversed __ ( issue33462:可逆dict ),因此请使用中间的 list tuple ,它们确实支持反向迭代:

On 3.7 and 3.6, they hadn't gotten around to implementing __reversed__ on dict and dict views (issue33462: reversible dict), so use an intermediate list or tuple, which do support reversed iteration:

d = {3: 'three', 2: 'two', 1: 'one'}
d = dict(reversed(list(d.items())))

3.6之前的版本,您需要集合.OrderedDict (用于输入和输出)以实现所需的结果.普通的 dict 直到CPython 3.6(作为实现细节)和Python 3.7(作为语言保证)都没有保留任何顺序.

Pre-3.6, you'd need collections.OrderedDict (both for the input and the output) to achieve the desired result. Plain dicts did not preserve any order until CPython 3.6 (as an implementation detail) and Python 3.7 (as a language guarantee).

这篇关于Python反向字典项目顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆