new to Python and had a question about dictionaries. I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it.
So if I have the dictionary:
d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10}
It isn't in that order if I view it or iterate through it, is there any way to make sure Python will keep the explicit order that I declared the keys/values in?
Using Python 2.6
解决方案
from collections import OrderedDict
OrderedDict((word, True) for word in words)
contains
OrderedDict([('He', True), ('will', True), ('be', True), ('the', True), ('winner', True)])
If the values are True (or any other immutable object), you can also use:
OrderedDict.fromkeys(words, True)