0
prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

for key in stock:
    print key
    print 'prince: %s' % prices[key]
    print 'stock: %s' % stock[key]

The output when I run this code is as follows:

orange
prince: 1.5
stock: 32
pear
prince: 3
stock: 15
banana
prince: 4
stock: 6
apple
prince: 2
stock: 0

Why is it not printing according the order in which the elements appear in the dictionary? For example, why isn't 'banana' printed first, as follows:

banana
price: 4
stock: 6
nbrooks
  • 18,126
  • 5
  • 54
  • 66
  • 1
    Because dictionaries are not ordered. – Christian Tapia Jun 22 '14 at 04:27
  • A Christian says, [dictionaries are not sorted](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) If you want a sorted list, you have to call `for key in sorted(stock.keys()` – mtik00 Jun 22 '14 at 04:37
  • @mtik00 That seems to produce an alphabetical sorting, when really OP seems to just want to keep them in the same order as they were added in – nbrooks Jun 22 '14 at 04:40

3 Answers3

1

Python dictionaries are unordered, meaning they won't remember the order you put elements in. This post has some answers that may be helpful to you if you are looking for more information on dictionaries.

You can create an ordered dictionary-equivalent using the OrderedDict datatype.

Community
  • 1
  • 1
Antrikshy
  • 2,918
  • 4
  • 31
  • 65
1

Dictionaries don't have an order. The point of a dictionary is to fetch items by a key which is provided by the programmer, so it doesn't make sense to maintain order; as long as it is quick and easy to fetch items by their key.

There is OrderedDict which will remember the order in which the keys were inserted.

For your case, it is better to rearrange your data:

stock = {'banana': {'price': 4, 'stock': 6}, 'apple': {'price': 2, 'stock': 0}}
for fruit, details in stock.iteritems():
    print('{0}'.format(fruit))
    print('Price: {0.price}'.format(details))
    print('Stock: {0.stock}'.format(details))

You can also just use tuple, like this:

stock = {'banana': (4, 6), 'apple': (2, 0)}
for fruit, details in stock.iteritems():
    price, stock = details
    print('{0}'.format(fruit))
    print('Price: {0}'.format(price))
    print('Stock: {0}'.format(stock))
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

Dictionaries are an unordered set of key:value pairs. They have no notion of order.

You can check out OrderedDict if you would like an ordered dictionary. Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

See: https://docs.python.org/2/library/collections.html

collections.OrderedDict

mqutub
  • 304
  • 2
  • 8