我想看一下Twitter上一个单词在推文中出现的频率。我使用Twitter API下载了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 总是这样做的吗?