python - 为特定键订购字典
问题描述
我想通过键的值订购一个字典。我阅读了本教程来对字典进行排序,但它没有指定如何按键对字典进行排序,或者我不明白如何。
tweets.json
我从使用以下代码命名的 json 中读取此数据
with open('tweets.json') as json_file:
json_data = json.load(json_file)
{
"json_data": [
{
"Tweets": "Today, it was my great honor to welcome and host the 2018 @NASCAR Cup Series Champion, @JoeyLogano and @Team_Penske to the @WhiteHouse! ",
"date": "Tue, 30 Apr 2019 23:21:16 GMT",
"id": 1123366738463162368,
"len": 159,
"likes": 23487,
"retweets": 5278,
"sentiment": 1,
"source": "Twitter for iPhone"
},
{
"Tweets": "....embargo, together with highest-level sanctions, will be placed on the island of Cuba. Hopefully, all Cuban soldiers will promptly and peacefully return to their island!",
"date": "Tue, 30 Apr 2019 21:09:13 GMT",
"id": 1123333508078997505,
"len": 172,
"likes": 69469,
"retweets": 22433,
"sentiment": 1,
"source": "Twitter for iPhone"
},
{
"Tweets": "If Cuban Troops and Militia do not immediately CEASE military and other operations for the purpose of causing death and destruction to the Constitution of Venezuela, a full and complete....",
"date": "Tue, 30 Apr 2019 21:09:13 GMT",
"id": 1123333506346749952,
"len": 189,
"likes": 75502,
"retweets": 28047,
"sentiment": 1,
"source": "Twitter for iPhone"
}
]
}
我想使用这个功能OrderedDict()
但我不知道如何指定密钥likes
我如何按喜欢的键对这个字典进行排序?
解决方案
您不需要OrderedDict
此处,因为您实际上是按键值对字典列表进行排序。您可以使用sorted
(使用itemgetter
而不是 alambda
来提高效率,但无论哪种方式都可以)。下面的内容会改变您的json_data
dict,以便列表likes
按键的值升序排序。
from operator import itemgetter
json_data['json_data'] = sorted(json_data['json_data'], key=itemgetter('likes'))
推荐阅读
- android - 在 EditText 中使用 Android LiveData 进行操作?
- solidity - 尝试在 nodejs 中使用 web3 和 ethersjs 进行煎饼交换交易时,交易一直失败
- arrays - 从多维结构中获取数据
- .net-5 - 为什么 .NET 5 中的引用类型没有 Interlocked.Read?
- html - 如何将 Bootstrap 4 列高限制为另一个列高?
- java - CodenameOne - 在主题中导入一组图像
- c - C Socket 代码在 LAN 内工作,但不能在 WAN 上工作?拒绝连接?
- spring - 带有登录用户过滤器的 JWT 的 Spring Security
- mysql - MySQL Count 在同一日期具有“开始”和“完成”条目的用户记录数?
- linear-programming - 如何使用二进制变量在 LPsolve 中添加依赖约束