简体   繁体   English

如何更改dict中键的索引?

[英]How to change the index of a key in dict?

I'm using Python 3.7 so dictionnaries are ordered.我正在使用 Python 3.7,因此订购了字典。 I have a dict like this: d = { 'a': 10, 'b': 20, 'c': 30} .我有一个这样的字典: d = { 'a': 10, 'b': 20, 'c': 30} I want to get: d = { 'a': 10, 'c': 30, 'b': 20,} .我想得到: d = { 'a': 10, 'c': 30, 'b': 20,} I know I can get the index of a key with d.index("a") , but I didn't find a way to change the index.我知道我可以使用d.index("a")获取键的索引,但我没有找到更改索引的方法。

One option is to use d.items().一种选择是使用 d.items()。 This will return a list [('a', 10), ('b', 20), ('c', 30)].这将返回一个列表 [('a', 10), ('b', 20), ('c', 30)]。 Lists can be easily rearranged however you want.列表可以根据需要轻松重新排列。 Check out https://www.w3schools.com/python/ref_list_sort.asp查看https://www.w3schools.com/python/ref_list_sort.asp

Try using OrderedDict from the collections library.尝试使用collections库中的OrderedDict Then you can change the order of the keys by using the move_to_end() method and sort the dictionary however you'd like.然后,您可以使用move_to_end()方法更改键的顺序,并根据需要对字典进行排序。

from collections import OrderedDict


data = OrderedDict({'a': 10, 'b': 20, 'c': 30})
print(data.keys())
# output: odict_keys(['a', 'b', 'c'])

data.move_to_end('b')
print(data.keys())
# output: odict_keys(['a', 'c', 'b'])

You should try something like this!你应该尝试这样的事情!

d[newKey] = d[oldKey]
del d[oldKey]

If the key is undefined it will raise an error如果键未定义,则会引发错误

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

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