Q:

Python extract top user name from json

I'm trying to get a sorted list or table of users from a loaded dict. I was able to print them as below but I couldn't figure out how to sort them in descending order according to the number of tweets the user name made in the sample. If I'm able to do that I might figure out how to track the to user as well. Thanks!
tweets = urllib2.urlopen("http://search.twitter.com/search.json?q=ECHO&rpp=100")
tweets_json = tweets.read() 
data = json.loads(tweets_json)                                                                                                              

for tweet in data['results']:                                                                                           
...    print tweet['from_user_name']                                                                                                                                                               
...    print tweet['to_user_name']                                                                                          
...    print  

A:

tweets = data['results']
tweets.sort(key=lambda tw: tw['from_user_name'], reverse=True)

Assuming tw['from_user_name'] contains number of tweets from given username.
If tw['from_user_name'] contains username instead then:
from collections import Counter

tweets = data['results']
count = Counter(tw['from_user_name'] for tw in tweets)
tweets.sort(key=lambda tw: count[tw['from_user_name']], reverse=True)

To print top 10 usernames by number of tweets they send, you don't need to sort tweets:
print("\n".join(count.most_common(10)))

