Pregunta

Let's say I have this dictionary:

mydict = {'1': ['a', 'b', 'c'], 
          '2': ['d', 'e', 'f'], 
          '3': ['g', 'h', 'i'], 
          '4': ['j', 'k', 'l'], 
          '5': ['m', 'n', 'o']}

According to the Python documentation,

The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order

When I call mydict.keys() method, it will give me a list of keys in the mydict without any particular order like this:

['1', '3', '2', '5', '4']

My Question is does the key list(above) generated by .keys() method has the same order everytime I call it? I have tried it using for loop like this:

for i in range(100):
    print mydict.keys()

It seems to me that the resulting list has always the same order. But I just want to confirm that there is no hidden case that will change the order of output list.

In other word, if i use mydict.keys()[0] , will I get the same item every time?

¿Fue útil?

Solución

You should never rely on ordering when using a dict. Even though you test it 1 billion times and it looks homogeneous, there's nothing in the specification that states that it is, and thus there can be some hidden code that says "every full moon that begins on an even day, change the order".

If you want to rely on ordering, then use OrderedDict from collections.

Otros consejos

My Question is does the key list(above) generated by .keys() method has the same order everytime I call it?

If there are no intervening modifications to the dictionary, then the order would be the same.

Quoting from the documentation:

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). The same relationship holds for the iterkeys() and itervalues() methods: pairs = zip(d.itervalues(), d.iterkeys()) provides the same value for pairs. Another way to create the same list is pairs = [(v, k) for (k, v) in d.iteritems()].

The short answer is no, you cannot rely on the order. The reason is that the keys are hashed and placed in a table accordingly. The size of the table is adjusted up whenever the dictionary is 2/3 full (I think this is the number) in order to avoid too many collisions and maintain an O(1) access time, and adjusted down (I think when it is 1/3rd full), to manage memory utilization.

Because it is a hash table, the sequence in which the dictionary is constructed will affect the ordering of the keys. The hash function may change in future versions...

If you need to use the keys in a reliable order, you could look into collections OrderedDict, this might be what you are looking for. [edit: I just noticed you are using python 2.7, OrderedDict is only available in Python 3.+]

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top