-1

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.

eternal_student
  • 476
  • 2
  • 13
  • 1
    Please retake the [tour], read [what's on-topic here](/help/on-topic), [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953), and provide a [mre]. "Implement this feature for me" is off-topic for this site. You have to _make an honest attempt_, and then ask a _specific question_ about your algorithm or technique. – Pranav Hosangadi Jun 23 '21 at 15:00
  • @PranavHosangadi OK, sorry – eternal_student Jun 24 '21 at 19:34

1 Answers1

1

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:

Stef
  • 9,779
  • 2
  • 14
  • 27