Reputation: 716
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
Reputation: 15515
Suggested algorithm:
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;key: value
pair in the old dictionary, add it to the new dictionary.For step 3, you can use dict.update
or |=
.
Further reading:
dict.update
and |=
;|=
;collections.OrderedDict
instead of dict
, which is no longer necessary since Python 3.7.Upvotes: 1