订购字典以获取特定键

时间:2019-05-06 22:29:07

标签: python python-3.x sorting dictionary

我想通过键的值对字典进行排序。我阅读了本教程,对字典进行排序,但是没有指定如何通过键对字典进行排序,或者我不知道该怎么做。

我使用以下代码从名为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

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

1 个答案:

答案 0 :(得分:1)

这里您不需要OrderedDict,因为您实际上是按键值对字典列表进行排序的。您可以使用sorted来做到这一点(为了提高效率,可以使用itemgetter而不是lambda,但是您可以选择其中任何一种方式)。以下内容会更改您的json_data字典,以使列表按likes键的值升序排列。

from operator import itemgetter

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