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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.