简体   繁体   English

根据首选顺序更改字典键的顺序

[英]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.字典可能没有preferred_order列表中的所有键,并且可能有没有出现在列表中的键。

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.location没有添加到字典中,不在preferred_order中的键在最后。

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;迭代通过preferred_order :每keypreferred_order ,添加key: value到新的字典,如果它存在于旧字典,从旧字典中删除;
  3. for every remaining key: value pair in the old dictionary, add it to the new dictionary.对于旧字典中的每个剩余key: value对,将其添加到新字典中。

For step 3, you can use dict.update or |= .对于第 3 步,您可以使用dict.update|=

Further reading:进一步阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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