Python字典没有保持秩序 [英] Python dictionary is not staying in order
问题描述
我创建了一个字母字典,其值从 0 开始,并根据单词文件增加一定数量.我对初始字典进行了硬编码,我希望它保持按字母顺序排列,但根本没有.我希望它按字母顺序返回字典,基本上与初始字典保持一致.
I created a dictionary of the alphabet with a value starting at 0, and is increased by a certain amount depending on the word file. I hard coded the initial dictionary and I wanted it to stay in alphabetical order but it does not at all. I want it to return the dictionary in alphabetical order, basically staying the same as the initial dictionary.
我怎样才能保持秩序?
from wordData import*
def letterFreq(words):
totalLetters = 0
letterDict = {'a':0,'b':0,'c':0,'d':0,'e':0,'f':0,'g':0,'h':0,'i':0,'j':0,'k':0,'l':0,'m':0,'n':0,'o':0,'p':0,'q':0,
'r':0,'s':0,'t':0,'u':0,'v':0,'w':0,'x':0,'y':0,'z':0}
for word in words:
totalLetters += totalOccurences(word,words)*len(word)
for char in range(0,len(word)):
for letter in letterDict:
if letter == word[char]:
for year in words[word]:
letterDict[letter] += year.count
for letters in letterDict:
letterDict[letters] = float(letterDict[letters] / totalLetters)
print(letterDict)
return letterDict
def main():
filename = input("Enter filename: ")
words = readWordFile(filename)
letterFreq(words)
if __name__ == '__main__':
main()
推荐答案
Python 3.7+ 更新:
字典现在正式维护插入顺序Python 3.7 及更高版本.
Dictionaries now officially maintain insertion order for Python 3.7 and above.
Python 3.6 更新:
字典在 Python 3.6 中保持插入顺序,但是,这个被视为实现细节,不应依赖.
Dictionaries maintain insertion order in Python 3.6, however, this is considered an implementation detail and should not be relied upon.
原始答案 - 直到并包括 Python 3.5:
字典没有排序,也不为您保留任何顺序.
Dictionaries are not ordered and don't keep any order for you.
你可以使用一个有序字典,它维护插入顺序:
You could use an ordered dictionary, which maintains insertion order:
from collections import OrderedDict
letterDict = OrderedDict([('a', 0), ('b', 0), ('c', 0)])
或者你可以只返回字典内容的排序列表
Or you could just return a sorted list of your dictionary contents
letterDict = {'a':0,'b':0,'c':0}
sortedList = sorted([(k, v) for k, v in letterDict.iteritems()])
print sortedList # [('a', 0), ('b', 0), ('c', 0)]
这篇关于Python字典没有保持秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!