惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
博客园 - 三生石上(FineUI控件)
D
DataBreaches.Net
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
GbyAI
GbyAI
P
Proofpoint News Feed
Microsoft Security Blog
Microsoft Security Blog
月光博客
月光博客
I
InfoQ
V
Visual Studio Blog
罗磊的独立博客
Engineering at Meta
Engineering at Meta
Vercel News
Vercel News
Jina AI
Jina AI
L
LangChain Blog
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
B
Blog
The Cloudflare Blog
小众软件
小众软件
雷峰网
雷峰网
V
V2EX
人人都是产品经理
人人都是产品经理
Stack Overflow Blog
Stack Overflow Blog

cywhat's blog

Mac修改brew源 Java编译出现java.lang.ExceptionInInitializerError Linux生成自定义名称的ssh证书 Jmeter进行分布式压测 Python创建并上传自己的pip依赖包 Django操作异步任务 Linux卸载RabbitMQ Linux安装RabbitMQ ValueError:invalid UnorderedObjectListWarning:Pagination May Yield Inconsistent Results With an Unordered Object_list Jenkins端口修改之后没有生效 Mac出现xxx@bogon Linux忘记mysql密码解决办法 Pkg_resources.DistributionNotFound:The Supervisor==3.4 Failing Package Is: Mysql Community Libs Compat 5.7.37 1.el7 2022收一收 搭建IOS和Android性能监控工具 Jenkins添加html报告并发送到邮箱 Jenkins插件无法安装解决 Jenkins报错 Bash:newman:command Not Found Linux安装newman生成postman脚本报告 MoudleNotFoundError: No module named 'xxx' Failed to Extract Shortcode:template for Shortcode Admonition Not Found Zsh Problem Compinit503 No Such File or Directory Usr Local Share Zsh Site Django删除表重建 魔戒使用教程 Python获取当前位置所在行数以及函数名 Django的csrf防御机制 Django连接Mysql配置 Mac安装mysql5.7
Python如何让字典保持有序存储
cywhat · 2022-07-22 · via cywhat's blog

前景

众所周知python的字典dict是无序的和元组不同,但是一些特定场景,又需要字典中的数据是有序的,分享并记录下如何解决

注意

python3.7之后字典就更改为有序存储了,不需要重新定义,python3.7之前的可以用以下方法重新定义为有序存储

案例

无序演示

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
dict1 = {'a':1,"b":2,"c":3}

print(dict1)

#多次执行,结果如下:
{'a':1,"b":2,"c":3}

{'a':1,"b":2,"c":3}

{"b":2,'a':1,"c":3}

{"c":3,'a':1,"b":2}

{'a':1,"c":3,"b":2}

解决

有序演示

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import collections
dict2 = collections.OrderedDict()
dict2['a'] = 1 
dict2['b'] = 2
dict2['c'] = 3

print(dict2)

#多次执行,结果如下:
{'a':1,"b":2,"c":3}

{'a':1,"b":2,"c":3}

{'a':1,"b":2,"c":3}

{'a':1,"b":2,"c":3}

{'a':1,"b":2,"c":3}

关注一下再走吧

公众号 小程序

赞赏支持

微信打赏 支付宝打赏