简体   繁体   中英

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.

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:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM