Home > other >  How to change the order of key-value pairs in a dictionary?
How to change the order of key-value pairs in a dictionary?

Time:06-06

How to move the last key-value pair to the first place?

d = {1 : 'a', 2 : 'b', 3 : 'c'}

Here is what I'm trying to get

d = {3 : 'c', 1 : 'a', 2 : 'b'}

I have no idea how to implement it.

CodePudding user response:

One approach would be:

d = {1: "a", 2: "b", 3: "c"}
print(dict([d.popitem()]) | d)

output

{3: 'c', 1: 'a', 2: 'b'}

popitem() gives a tuple of the last key-value pair in the dictionary. We put it into a list to create an iterable of pair items, then we can call dict() on it.

from documentation:

...Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.

This works on version 3.9 and above. Since version 3.7, insertion order of the dict is guaranteed to be preserved. Since version 3.9 , dictionaries support union | operator.

CodePudding user response:

It works only if your Python version maintains insertion order (Python 3.7 and later), but you can try:

d = {1 : 'a', 2 : 'b', 3 : 'c'}
# last key
last_k = next(reversed(d))
# put the last key-value pair before the rest
d = {last_k: d.pop(last_k), **d}
d
# {3: 'c', 1: 'a', 2: 'b'}

CodePudding user response:

For a systematic approach, when the dict is "big", you can a mapper which contains a list of old key-new key and then use a dict-comprehension to get a dictionary with the new ordering.

d = {1 : 'a', 2 : 'b', 3 : 'c'}

mapper = [(1, 3), (2, 1), (3, 2)]

new_d = {k_new: d[k_new] for _, k_new in mapper}
  • Related