1

I want to order a dict by the value of a key. I read this tutorial to sort a dict but it doesn't specify how to order a dict by key or I don't understand how .

I read this data from a json named tweets.json with the following code

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"
    }
   ]
}

I want to use this function OrderedDict() but I don't know how to specify the key likes

How I can sort this dict by the key likes ?

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

1

You don't need an OrderedDict here since you are really sorting a list of dicts by key value. You can do that with sorted (using itemgetter instead of a lambda for efficiency but you could do it either way). The below mutates your json_data dict so that the list is sorted ascending by the values of the likes keys.

from operator import itemgetter

json_data['json_data'] = sorted(json_data['json_data'], key=itemgetter('likes'))
benvc
  • 14,448
  • 4
  • 33
  • 54