Tuesday, November 8, 2011

The order of Python dictionary

Dictionary is one of the most useful datatype in Python. It provides quick access to the value stored with the key. For example,
>>>author={'Harry Potter':'JK Rowling'}
>>>print author['Harry Potter']
JK Rowling
The advantage of dictionary is quick access to the value associated with the key. The time complexity of searching and insertion are both O(1), which is much faster than array (i.e., list in Python). However, the disadvantage is that dictionary is implemented by hash table, which doesn't keep the original order in which the keys and values are inserted. For example,
>>>author={'A Tale of Two Cities':'Charles Dickens','Harry Potter':'JK Rowling'}
[('Harry Potter', 'JK Rowling'), ('A Tale of Two Cities', 'Charles Dickens')]
Where the order of the printed out results is not same as the original order in the initialization. To solve this problem, use following codes to display the dictionary contents by the order of keys.
keys = author.keys()
for key in keys:
    print "key=%s, value=%s" % (key,author[key])

No comments:

Post a Comment