排序一个dicts列表

时间:2014-01-23 17:27:22

标签: python list twitter hashtag

我想知道哪些主题标签在推文中使用最多,所以我确实喜欢这个

cursor = db.execute("SELECT text FROM myTable WHERE text LIKE '%#%' ")
for row in cursor:      
    for word in (re.findall(r"#(\w+)", row[0])):
        top_hashtags.append(word)
top_hashtags = {i:top_hashtags.count(i) for i in set(top_hashtags)}
print sorted(top_hashtags, key=lambda x: x[0])

结果是错误的。

我用过:print sorted(top_hashtags, key=lambda x: x[0]) 但我认为这不符合我的要求。

2 个答案:

答案 0 :(得分:3)

这是为Counter构建的那种东西:

from collections import Counter
c = Counter(top_hashtags)
print(c.most_common(5)) # print 5 most common hashtags with counts

要回答您的具体问题,请按值使用

对字典键进行排序
top_ht_dict = {i:top_hashtags.count(i) for i in set(top_hashtags)}

sorted(top_ht_dict, key=top_ht_dict.get, reverse=True)
                                       # ^ most common first

答案 1 :(得分:0)

你想要的是print sorted(top_hashtags, key=top_hashtags.get, reverse=True)

这将根据主题标签显示的次数对主题标签进行排序,reverse=True导致主题标签的顺序相反(即列表中最常见的主题标签)