python - 为什么我的字典是用 python 排序的?

标签 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

不要误会我的意思,我的字典已经这样排序了,这真是太好了,但是如何呢? 是我添加到字典中的方式还是什么?

编辑

我试着用整数作为键和一些字符串作为值来制作一个字典。我添加的键没有特别的顺序,但是当我打印这本字典时,它又是按键排序的。 这是 python 总是做的事情吗?

最佳答案

“无序”用词不当 - 它们是任意排序的,由实现决定。具体来说,保证顺序是任意的,但一致(在 python 解释器 [1] 的单个实例中)。

至于为什么你会出现这种行为 - 你正在使用 int 作为你的键。碰巧在 cPython 中,inthash 就是它本身。因此:

d = dict(zip(range(100),' '*100))
print(d)

将始终以数字顺序显示键,这要归功于该实现细节。但是这个:

d = dict((L, i) for i, L in enumerate('abcdefg'))
print(d)

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


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

关于python - 为什么我的字典是用 python 排序的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23438671/

相关文章:

c++ - C++中的 map 与多 map (性能)

javascript - 谷歌地图 : get user's location like google

python - 使用字典映射 numpy 数组?

python - 将临时值分配给循环python中的变量

python - 创建 sublime text 插件同时支持 ST2 和 ST3

python - 将包含列表的字典的值替换为列表的其他项目

c# - 在哈希集字典中查找值的组合

python - 空记录数组的单元测试相等性

python - 检查模板 Django 中变量中字符串的某些部分

swift - 使用十进制数字键在字典中查找最近的键