Home > Software design >  Sort a dictionary based on the keys of another dictionary
Sort a dictionary based on the keys of another dictionary

Time:09-08

I have a dictionary with a specific order of keys(the values don't matter). I have another dictionary with the same keys, but not in the same order:

dict_1 = {"name" : "Joe", "class" : "8", "marks" : "80"}
dict_2 = {"class" : "9", "marks" : "90", "name" : "Adam"}

Now after sorting dict_2, I want it to be as {"name" : "Adam", "class" : "9", "marks" : "90"}. I know that this is possible since dictionaries are ordered by default in Python 3, but I couldn't get any solution even after a lot of research.

CodePudding user response:

Keys are sorted in insertion order. That means that you need to either remove the keys from dict_2 and add them back in the right order, or just make a new dictionary.

You can get the same keys as dict_1 by copying the entire dictionary and reassigning the values:

result = dict_1.copy()
for key in result:
    result[key] = dict_2[key]

You can shorten the loop to

result.update(dict_2)

A similar result would be obtained from merging the dictionaries in order, with dict_1 used to establish the order of keys, and dict_2 to supply the values:

{**dict_1, **dict_2}

As of Python 3.9, PEP-0584 introduces the union operator for dictionaries, so you can write the same thing as

dict_1 | dict_2

You can also just iterate over the keys in dict_1:

result = {k: dict_2[k] for k in dict_1}

Or you can pop-and-add if you want to keep the same object for some reason:

for key in dict_1:
    dict_2[key] = dict_2.pop(key)

CodePudding user response:

What are you actually trying to accomplish by having the dictionary keys in the same order? Presumably you want to iterate over them in some order, say to print them. Instead of rearranging every dictionary, why not simply have a list of the keys in the order you want them, and iterate over that list to get the values for that key in that order?

keys = ["class", "marks", "name"]
for key in keys:
    print(key, dict1[key])

If you really do want to rearrange the dictionaries, the most straightforward way (IMHO) is to create a new dictionary in the desired order.

keys = ["class", "marks", "name"]    
dict1 = {key: dict1[key] for key in keys}

Write a function for doing this so you don't need to repeat yourself.

CodePudding user response:

This can be done by building a new dictionary using the keys from dict_1.

dict_1 = {"name" : "Joe", "class" : "8", "marks" : "80"}
dict_2 = {"class" : "9", "marks" : "90", "name" : "Adam"}

key_list = list(dict_1)

dict_3 = {}
for key in key_list:
    dict_3[key] = dict_2[key]

dict_3 now contains the values from dict_2, but using the key order of dict_1. Of course, you could also use this method to build dict_2 to begin with.

  • Related