python 把字典变为有序

网友投稿 254 2022-08-25


python 把字典变为有序

1. 使用OrderedDict

if __name__ == "__main__": from collections import OrderedDict columns = {"column_1": "value1", "column_3": "value3","column_2": "value2","column_5": "value5","column_4": "value4"} new_dict = OrderedDict(sorted(columns.items(), key=lambda x: int(x[0].split("_")[1]))) print(new_dict)# 输出的结果为{"column_1": "value1", "column_2": "value2","column_3": "value3","column_4": "value4","column_5": "value5"}

2. 添加时顺序保存

```pythonif __name__ == "__main__": import collections old_dict = collections.OrderedDict() old_dict["column_1"] = "value1" old_dict["column_2"] = "value2" old_dict["column_3"] = "value3" old_dict["column_4"] = "value4" old_dict["column_5"] = "value5" print(old_dict)# 输出的结果为{"column_1": "value1", "column_2": "value2","column_3": "value3","column_4": "value4","column_5": "value5"}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java Vector实现班级信息管理系统
下一篇:python 把字典变为有序(python怎么读)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~