为什么我的字典在python中排序?

Eer*_*ame 2 python dictionary

我想知道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
Run Code Online (Sandbox Code Playgroud)

不要误会我的意思,我的字典已经按照这样的顺序排序了,但是怎么样?这是我添加到字典或其他东西的方式吗?

编辑

我试着用整数作为键和一些字符串作为值来制作字典.我没有按顺序添加密钥,但是当我打印这个字典时,它再次按键排序.这是python总能做到的吗?

roi*_*ppi 7

"无序"是用词不当 - 它们是任意排序的,留给实施.具体来说,保证顺序是任意的,但是一致的(在python解释器的单个实例中[1]).

至于为什么你会得到这种行为 - 你使用ints作为你的钥匙.碰巧在cPython中,hasha int本身就是这样.这样:

d = dict(zip(range(100),' '*100))
print(d)
Run Code Online (Sandbox Code Playgroud)

由于实现细节,将始终以数字顺序出现密钥.但是这个:

d = dict((L, i) for i, L in enumerate('abcdefg'))
print(d)
Run Code Online (Sandbox Code Playgroud)

(很可能)不会按字母顺序打印出来.


[1]字符串散列行为可能因解释器实例而异,具体取决于您正在运行的python版本.Python 3为字符串键的散列引入了"随机种子"作为安全措施.您可以在python 2.7上启用该行为python -R.