1

As of Python 3.7, dictionaries are "ordered", where iteration is based on "insertion order".

I would like a dictionary in Python where iteration is based on the alphabetical order of the keys, i.e. the dictionary is sorted alphabetically by key.

That is, the following dictionary:

dictionary = {}
dictionary["b"] = 1
dictionary["a"] = 2

Will result in the following output:

for key in dictionary:
    print(key) # a, b

Is there some built-in Python class for "sorted dictionaries", similar to how we have OrderedDict for insertion order?

Note: I do not believe that this is a duplicate of any existing questions, which seem to only mention:

  • Ordered dictionaries (dictionaries sorted by insertion-order) -- this is not what I'm looking for.
  • Dictionaries sorted by value -- I'm looking for dictionaries sorted by key.
  • Sorting a dictionary after-the-fact rather than automatically (and efficiently) as elements are added/removed.

I have done many Google searches and couldn't find an answer.

David Callanan
  • 5,601
  • 7
  • 63
  • 105

1 Answers1

2

There is actually a solution, which is from Mark Summerfield : Rapid GUI Programming with Python and I would humbly transfer it here. All the respect for Mark :)

import bisect

class CustomOrderedDict(object):
    def __init__(self, dictionary=None):
        self.__keys = {}
        self.__dict = []
        if dictionary is not None:
            if isinstance(dictionary, CustomOrderedDict):
                self.__dict = dictionary.__dict.copy()
                self.__keys = dictionary.__keys[:]
            else:
                self.__dict = dict(dictionary).copy()
                self.__keys = sorted(self.__dict.keys())

    def getAt(self, index):
        return self.__dict[self.__keys[index]]

    def setAt(self, index, value):
        self.__dict[self.__keys[index]] = value
        return self.__dict[self.__keys[index]]

    def __getitem__(self, key):
        return self.__dict[key]

    def __setitem__(self, key, value):
        if key not in self.__dict:
            bisect.insort_left(self.__keys, key)
        self.__dict[key] = value

    def __delitem__(self, key):
        i = bisect.bisect_left(self.__keys, key)
        del self.__keys[i]
        del self.__dict[key]

    def setdefault(self, key, value):
        if key not in self.__dict:
            bisect.insort_left(self.__keys, key)
        return self.__dict.setdefault(key, value)

    def pop(self, key, value=None):
        if key not in self.__dict:
            return value
        i = bisect.bisect_left(self.__keys, key)
        del self.__keys[i]
        return self.__dict.pop(key, value)

    def popitem(self):
        item = self.__dict.popitem()
        i = bisect.bisect_left(self.__keys, item[0])
        del self.keys[i]
        return item

    def has_key(self, key):
        return key in self.__dict

    def __contains__(self, key):
        return key in self.__dict

    def __len__(self):
        return len(self.__dict)

    def keys(self):
        return self.__keys[:]

    def values(self):
        return [self.__dict[key] for key in self.__keys]

    def __iter__(self):
        return iter(self.__keys)

    def iterkeys(self):
        return iter(self.__keys)

    def itervalues(self):
        for key in self.__keys:
            yield self._dict[key]

    def iteritems(self):
        for key in self.__keys:
            yield key, self.__dict[key]

    def copy(self):  # shallow copy
        dictionary = CustomOrderedDict()
        dictionary.__keys = self.__keys[:]
        dictionary.__dict = self.__dict.copy()
        return dictionary

    def clear(self):
        self.__keys = []
        self.__dict = {}

    def __repr__(self):
        pieces = []
        for key in self.__keys:
            pieces.append("%r: %r" % (key, self.__dict[key]))  
        return "CustomOrderedDict({%s})" % ", ".join(pieces)


t = CustomOrderedDict(dict(s=1, a = 2, b =100, c = 200))


print t

RESULT :

CustomOrderedDict({'a': 2, 'b': 100, 'c': 200, 's': 1})
baskettaz
  • 741
  • 3
  • 12