eternal_student
eternal_student

Reputation: 716

Changing order of dictionaries keys based on preferred order

The input is a dictionary, for example:

{'first_name':'Jane', 'occupation': 'astronaut', 'age':27, 'last_name':'Doe'}

The keys need to be rearranged to be in a specific order, given in a list, for example:

preferred_order = ['first_name', 'last_name', 'age', 'location']

The dictionary might not have all the keys in the preferred_order list, and might have keys that don't appear on the list.

In this specific case, the result of the sorting should be:

{'first_name':'Jane', 'last_name':'Doe', 'age':27, 'occupation': 'astronaut'}

Key location didn't get added to the dictionary, and the keys not in preferred_order are at the end.

Upvotes: 0

Views: 763

Answers (1)

Stef
Stef

Reputation: 15515

Suggested algorithm:

  1. Create a new, initially empty, dictionary;
  2. Iterate through preferred_order: for every key in preferred_order, add key: value to the new dictionary if it exists in the old dictionary, and remove it from the old dictionary;
  3. for every remaining key: value pair in the old dictionary, add it to the new dictionary.

For step 3, you can use dict.update or |=.

Further reading:

Upvotes: 1

Related Questions