python - 用字符串数字键对字典进行数字排序的最 Pythonic 方法是什么?
问题描述
这是我的格式,dict
:
{
"server" : {
"2" : {
name : "Chris",
text : "Hello!"
},
"1" : {
name : "David",
text : "Hey!"
}
}
}
dict['server']
尽管键是字符串,但如何按数字排序?我能想出的所有方法都需要多个名称,而且一点也不像 Pythonic。
解决方案
使用collections.OrderedDict
前任:
import collections
d = {
"server" : {
"2" : {
"name" : "Chris",
"text" : "Hello!"
},
"1" : {
"name" : "David",
"text" : "Hey!"
}
}
}
print collections.OrderedDict(sorted(d["server"].items(), key=lambda x: int(x[0])))
输出:
OrderedDict([('1', {'text': 'Hey!', 'name': 'David'}), ('2', {'text': 'Hello!', 'name': 'Chris'})])
推荐阅读
- flutter - 通知浮动弹出菜单
- python - 如何在 PIL 的 putpixel 中使用灰度颜色?
- laravel - 对于这个请求结果是 For 还是 Foreach?
- jquery - 使用 jQuery 处理 JSON 数据
- facebook - Xamarin 表单 + IdentityServer + 外部提供程序 (Facebook/Google)
- bootstrap-4 - bootstrap 4 pull/float-right 不适用于 psd
- amazon-web-services - 将子域指向 AWS 并将根指向 bluehost
- html - 在反应项目 html 5 中,拖放在浏览器上有效,但在移动屏幕上无效
- java - Adding CA Certificate to Java Buildpack for PCF Deployment
- css - 如何调整 MediaWiki 中列表项之间的间距?