【问题标题】:Sort a list of dicts对字典列表进行排序
【发布时间】:2014-02-14 10:06:06
【问题描述】:

我想知道推文中使用最多的主题标签,所以我喜欢这个

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]) 但我认为它并没有像我想要的那样工作。

【问题讨论】:

  • 这里没有字典列表。
  • 输入这段代码时top_hashtags是什么类型,为什么要重写为dict?

标签: python list twitter hashtag


【解决方案1】:

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

【讨论】:

  • 你可以使用top_ht_dict.get作为key。
【解决方案2】:

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

这将根据主题标签出现的次数对主题标签进行排序,reverse=True 导致它以相反的顺序排列(即最常见的主题标签在列表中排在第一位)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    相关资源
    最近更新 更多