简体   繁体   中英

Change keys order in dict in Python 3.7+

Since dict object has native key order in Python 3.7+ ( https://docs.python.org/3/whatsnew/3.7.html ), there should be a way to manage the order. Is there an official documentation where I could read about it?

In my particular case I want to solve such issues without creating a new dictionary .

  1. Add a new key-value pair to the beginning.
  2. Sort the records in a dictionary by keys.

For the first one:

dct = {'b': 5, 'c': 6}
dct['a'] = 4  # What should be here
print(dct)  # I want it to be {'a': 4, 'b': 5, 'c': 6}

For the second one:

dct = {'b': 5, 'c': 6, 'a': 4}
dct.sort_somehow('...')  # What should be here
print(dct)  # I want it to be {'a': 4, 'b': 5, 'c': 6}

If you have to mutate the dict in-place, it's possible to use .clear() to clear it, then .update to put the new values in.

>>> dct = {'b': 5, 'c': 6, 'a': 4}
>>> sorted_key_values = sorted(dct.items())
>>> dct.clear()
>>> dct.update(sorted_key_values)
>>> dct
{'a': 4, 'b': 5, 'c': 6}

Note that this still consumes the amount of memory proportional to the number of key/value in the dict. It's very hard or impossible to sort it in-place (as in not using any extra memory), see python - Sort dict in-place - Stack Overflow .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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