简体   繁体   中英

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?

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)]

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM