Order of Dictionary Printout - Keeping Track of the Produce


#1




How does Python determine what order to print out the keys in dictionaries? When the code has been printed out it doesn't seem to be in numerical order or alphabetical order.


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

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

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


#2

Of course not. There are some methods to print out stuff sorted from Lower ones to Higher ones, but if you don't use them, the output will be every output that your code gives by sequentially.


#3

Hi, @dimitriparra ,

A Python dictionary, which is of type dict, is a hash table. Hash tables are considered to be unordered. A hash function is used to map each dict key to a location, or "bucket", in memory, where the item with that key is stored. It is possible for more than one key to map to the same bucket, in which case, a data structure, such as a linked list, can be used to maintain the items in that bucket.

Schemes to store dictionary items are designed for efficiency, rather than to preserve an order that is meaningful to the user. Therefore, to reliably output or otherwise deal with dict items in a desired order, one should sort or organize keys copied from a dict into another data type, such as a list, where the desired order can be maintained.

Though Codecademy presents Python 2.7.x, you can find relevant information at Python 3: 5.5. Dictionaries that might be of interest, most of which also applies to Python 2 versions.

For more general information on hash tables, see Wikipedia: Hash table and other sources via Google.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.