简体   繁体   English

如何颠倒python字典中的值而不是键的顺序?

[英]How to reverse order of values but not keys in a python dictionnary?

What is the best way to reverse order of values but not keys in a python dictionnary ?在 python 字典中颠倒值顺序而不是键的最佳方法是什么?

dictionnary = {'a': 3, 'b': 2, 'c': 1}
inversed_values = dictionnary.reverseValues()
print(inversed_values)

This should print out {'a': 1, 'b': 2, 'c': 3}这应该打印出{'a': 1, 'b': 2, 'c': 3}

You can convert values to list then reverse them then create dict like below:您可以将值转换为list然后反转它们,然后创建如下所示的dict

>>> dct = {'a': 3, 'b': 2, 'c': 1}
>>> dict(zip(dct.keys(),list(dct.values())[::-1]))
{'a': 1, 'b': 2, 'c': 3}

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

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