简体   繁体   中英

when running for loop on dictionary in Python2

I am pretty new to python coming from C++ as my first language. Let say I have a dictionary as the following :

 price = {
 'banana' : 3,
 'apple' : 2,
 'strawberry' : 6
 }

and when I run for loop as the following :

 for i in price:
   print i

my output comes out to be in this order:

 strawberry, banana, apple

I thought for loop iterates an array or list in order. Does this not apply for dictionary? I expected the outcome to be "banana, apple, strawberry" since banana is the first key and strawberry is the last key in my dictionary.

What's going on in python2 that I do not understand?

In Python 2.7, Iterating over a dictionary does not guarantee the order the keys or values will be returned in.

You can use OrderedDict if you need it.

In Python 3.7 the order is apparently guaranteed but to be honest I would use OrderedDict just to make sure it's explicitly stated for readability's sake, again if you need it.

A dictionary does not remember the order in which elements are inserted. This is why when you iterate over it, the order is arbitrary. OrderedDict, on the other hand, keeps track of said order. The syntax is identical to using a regular dictionary and you will need to import the collections module. In your case

from collections import OrderedDict

price = OrderedDict()

price['banana'] = 3
price['apple'] = 2
price['strawberry'] = 6

for i in price:
   print(i)

should give you the desired result.

Note that even though you can create a regular dictionary and pass it as a parameter to the OrderedDict() constructor, the order will not be guaranteed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM