【发布时间】:2014-06-19 18:13:50
【问题描述】:
我想看看一个词在 twitter 的推文中出现的频率。我使用 Twitter API 从 twitter 下载了 500 条推文,并制作了一个字典,其中词频为键,与该频率对应的所有词的列表为值。
我一直认为字典总是无序的,所以我想以某种方式订购我的字典。但是当我看它时,它已经按从低到高的键顺序排列了。这怎么可能?
这是我使用的代码:
def countWords(cleanDict):
reverseDict = {}
FreqDict = {}
count = 1
for tweet_id in cleanDict:
tweet = cleanDict[tweet_id]
wordList = tweet.split()
for word in wordList: # Creates a dictionary with words as keys and
# frequencies as values
if word in reverseDict:
reverseDict[word] += 1
else:
reverseDict[word] = 1
for word in reverseDict: # Creates a dictionary with frequencies as keys and
# lists of words as values
if reverseDict[word] in FreqDict:
temp = FreqDict[freqDict[word]]
temp.append(word)
FreqDict[freqDict[word]] = temp
else:
FreqDict[freqDict[word]] = [word]
return FreqDict
countWords(cleanDict) # cleanDict is a dictionary with tweet ID's as keys and
# tweets as values
不要误会我的意思,我的字典已经被这样排序真是太好了,但是如何呢? 是我添加到字典的方式还是什么?
编辑
我尝试制作一个以整数为键、一些字符串为值的字典。我没有按特定顺序添加键,但是当我打印这本字典时,它再次按键排序。 这是python总是做的事情吗?
【问题讨论】:
-
它们的下载顺序是什么?
-
你怎么知道它被订购了?你在哪里看?它是如何显示的?底层表示是无序的,但这并不意味着其他东西不能以有序的方式表示它。
-
@Drewdin 下载的最后一条推文是发布的最后一条推文。最后下载的第二条是最后一条推文发布的第二条推文,依此类推,一直到第 500 条推文
-
@g.d.d.c 我刚刚将它打印到我的 shell
标签: python dictionary