Skip to content

Instantly share code, notes, and snippets.

@stevekm
Created October 27, 2016 04:31
Show Gist options
  • Save stevekm/b722712e40df6cf5886af4e6aa7265db to your computer and use it in GitHub Desktop.
Save stevekm/b722712e40df6cf5886af4e6aa7265db to your computer and use it in GitHub Desktop.
Ordered default dict in Python 2.7 (and maybe 3)

http://stackoverflow.com/questions/6190331/can-i-do-an-ordered-default-dict-in-python

# from collections import OrderedDict, defaultdict
import collections
class OrderedDefaultDict(collections.OrderedDict, collections.defaultdict):
    def __init__(self, default_factory=None, *args, **kwargs):
        #in python3 you can omit the args to super
        super(OrderedDefaultDict, self).__init__(*args, **kwargs)
        self.default_factory = default_factory

foo = OrderedDefaultDict(dict)
bar = ["a", "b", "c", "d"]
baz = ["jj", "kk", "ll", "mm"]
fin = [23, 57, 99, 10]
foo2 = collections.defaultdict(dict)

for i in bar:
    for k in baz:
        for q in fin:
            foo[i][k] = q
            foo2[i][k] = q

for key in foo.iterkeys():
    print key

for key in foo2.iterkeys():
    print key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment