[英]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:建议算法:
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
:每key
在preferred_order
,添加key: value
到新的字典,如果它存在于旧字典,从旧字典中删除;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:进一步阅读:
dict.update
and |=
; 关于dict.update
和|=
文档;|=
;更多关于|=
;collections.OrderedDict
instead of dict
, which is no longer necessary since Python 3.7.您可以在 stackoverflow 上搜索“按键排序字典”,但请注意,大多数答案都已过时,建议使用collections.OrderedDict
而不是dict
,自 Python 3.7 以来不再需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.