Skip to content

Instantly share code, notes, and snippets.

@msabramo
Created March 15, 2011 18:04
Show Gist options
  • Save msabramo/871155 to your computer and use it in GitHub Desktop.
Save msabramo/871155 to your computer and use it in GitHub Desktop.
A demonstration of the difference between a regular (unordered) dictionary and collections.OrderedDict
#!/usr/bin/env python
# A demonstration of the difference between a regular (unordered) dictionary
# and collections.OrderedDict
# See http://docs.python.org/library/collections.html#collections.OrderedDict
from collections import OrderedDict
def unordered_dict(dict_type):
d = dict_type()
for i in range(26):
d[chr(ord('a') + i)] = i
return d
print '*** dict ***'
for key in unordered_dict(dict).items():
print key
print '*** OrderedDict ***'
for key in unordered_dict(OrderedDict).items():
print key
marca@ladyproud-lm:~/python$ ./dict_test.py
*** dict ***
('a', 0)
('c', 2)
('b', 1)
('e', 4)
('d', 3)
('g', 6)
('f', 5)
('i', 8)
('h', 7)
('k', 10)
('j', 9)
('m', 12)
('l', 11)
('o', 14)
('n', 13)
('q', 16)
('p', 15)
('s', 18)
('r', 17)
('u', 20)
('t', 19)
('w', 22)
('v', 21)
('y', 24)
('x', 23)
('z', 25)
*** OrderedDict ***
('a', 0)
('b', 1)
('c', 2)
('d', 3)
('e', 4)
('f', 5)
('g', 6)
('h', 7)
('i', 8)
('j', 9)
('k', 10)
('l', 11)
('m', 12)
('n', 13)
('o', 14)
('p', 15)
('q', 16)
('r', 17)
('s', 18)
('t', 19)
('u', 20)
('v', 21)
('w', 22)
('x', 23)
('y', 24)
('z', 25)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment