Josh
Josh

Reputation: 12791

Default ordered dictionaries in Python 2.7.x

Besides the answers from ~3 years ago in this question:

Can I do an ordered, default dict in Python?

Have any implementations been adopted into recent versions of Python?

If not, why not?

Upvotes: 0

Views: 8934

Answers (2)

mhlester
mhlester

Reputation: 23251

I'm afraid I'm not on 2.7, so cannot test, but this should reimplement a defaultdict subclassed from OrderedDict:

from collections import OrderedDict

class DefaultOrderedDict(OrderedDict):
    def __init__(self, default):
        self.default = default
    def __getitem__(self, x):
        try:
            return OrderedDict.__getitem__(self, x)
        except KeyError:
            self[x] = self.default()
            return self[x]

Upvotes: 1

sshashank124
sshashank124

Reputation: 32189

No, for default options, you will only have the built-in dictionary which is not ordered. If you do want an ordered dictionary, you will have to import the module OrderedDict.

from collections import OrderedDict
>>> od = OrderedDict([('a', 1), ('b', 2), ('c', 3)])

You do, however, have the option of creating a list of tuples which will maintain its order.

Instead of:

a = {'a': 1, 'b': 2, 'c':3}

you would do it as:

a = [('a', 1), ('b', 2), ('c', 3)]

Upvotes: 5

Related Questions