1. List of dict data structure description:
"trends": [
{
"name": "Rick Gates",
"promoted_content": null,
"query": "%22Rick+Gates%22",
"tweet_volume": 135732,
"url": "http://twitter.com/search?q=%22Rick+Gates%22"
},
{
"name": "#TheBachelorette",
"promoted_content": null,
"query": "%23TheBachelorette",
"tweet_volume": 91245,
"url": "http://twitter.com/search?q=%23TheBachelorette"
},
{
"name": "#KremlinAnnex",
"promoted_content": null,
"query": "%23KremlinAnnex",
"tweet_volume": 42654,
"url": "http://twitter.com/search?q=%23KremlinAnnex"
}]
2. Sorting target:
Sort the elements in trends according to the value of tweet_volume.
3. Implementation code:
The following 4 methods are all possible, the fourth one has better performance
1)trends = sorted(trends,key = lambda e:e['tweet_volume'],reverse = True)
2)trends = sorted(trends,key = lambda e:e.get('tweet_volume'),reverse = True))
3)trends = sorted(trends,key = lambda e:e.__getitem__('tweet_volume'),reverse = True))
4)trends = sorted(trends,key = itemgetter('tweet_volume'),reverse = True)
Description:
- When I select the key in the dict, I choose an index method like e['tweet_volume']. You can also choose e.get('tweet_volume') or e.__getitem__('tweet_volume') to get the key. Value of
- By using
operator
theitemgetter
function of the module , such data structure can be sorted very easily.from operator import itemgetter
4. Sotred() function prototype:
sorted(iterable[,key][,reverse])
iterable: Variables that need to be sorted (required)
key: specify the sorted element
reverse: specify whether to reverse the order, the default is false
For details, please refer to the previous article: Dist series (1): Sort according to the key and value of the dictionary
5. Lambda: anonymous function, the general form is
lambda arguments: expression
6. Considering that some data is NULL, it needs to be processed in advance:
For an empty tweet_volume set to 0, the complete code:
for item in trends:
if(item['tweet_volume'] is None):
item['tweet_volume'] = 0
trends = sorted(trends,key = lambda e:e['tweet_volume'],reverse = True)