简体   繁体   English

颠倒字典中元素的顺序

[英]Reverse the order of elements in a dictionary

If I have a dictionary dict1 = {1:'a', 2:'c', 'd':'gh'} and I want to reverse it so that dict2 = {'d':'gh', 2:'c', 1:'a'} .如果我有字典dict1 = {1:'a', 2:'c', 'd':'gh'}并且我想反转它以便dict2 = {'d':'gh', 2:'c', 1:'a'} I do not want to change the maping of the dictionary.我不想改变字典的映射。

I an doing this in python 3.7, which preserves element order in dictionaries.我在 python 3.7 中这样做,它保留了字典中的元素顺序。 Is there a function that would do this or what code would allow me to do this.是否有一个函数可以做到这一点,或者什么代码可以让我做到这一点。

you can convert to a list dict1.items then use the built-in function reversed :您可以转换为列表dict1.items然后使用内置函数reversed

dict(reversed(list(dict1.items())))

output:输出:

{'d': 'gh', 2: 'c', 1: 'a'}

You can usereversed() to reverse the dictionary:您可以使用reversed()来反转字典:

>>> dict1 = {1:'a', 2:'c', 'd':'gh'}
>>> dict2 = dict(reversed(dict1.items()))
>>> dict2
{'d': 'gh', 2: 'c', 1: 'a'}

As @kederrac helpfully pointed out in the comments, the above won't work in Python 3.7, only 3.8.正如@kederrac在评论中帮助指出的那样,上述内容在 Python 3.7 中不起作用,仅在 3.8 中起作用。 It will trigger a TypeError: 'dict_items' object is not reversible exception.它将触发TypeError: 'dict_items' object is not reversible异常。 To fix this you will need to cast list() to dict1.items() , as shown in @kederrac's answer.要解决此问题,您需要将list()dict1.items() ,如@kederrac 的回答所示。 Its probably safe to do this for safer, portable code anyways.无论如何,为了更安全、可移植的代码,这样做可能是安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM