首页 > 解决方案 > 为特定键订购字典

问题描述

我想通过键的值订购一个字典。我阅读了本教程来对字典进行排序,但它没有指定如何按键对字典进行排序,或者我不明白如何。

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

我如何按喜欢的键对这个字典进行排序?

标签: pythonpython-3.xsortingdictionary

解决方案


您不需要OrderedDict此处,因为您实际上是按键值对字典列表进行排序。您可以使用sorted(使用itemgetter而不是 alambda来提高效率,但无论哪种方式都可以)。下面的内容会改变您的json_datadict,以便列表likes按键的值升序排序。

from operator import itemgetter

json_data['json_data'] = sorted(json_data['json_data'], key=itemgetter('likes'))

推荐阅读