As I understand you want to have a data structure that gives you the same operations as dict, but if iterate over gives items in a precise order.
If this is the case you can override the methods that gives out iterables: the __iter__
method, the key
method, the values
method and the items
method (maybe there are others which I can't remember)
There is a basic class you can start off. (I.e this will only iterate over the elements you specified, but probably you want to extend to iterate over the other elements, too)
from collections import UserDict
class MyDict(UserDict):
def __init__(self, *args, **kwargs):
self.order = kwargs.pop('order')
super().__init__(*args)
def change_order(self, order: list):
self.order = order
def __iter__(self):
for key in self.order:
if key in self:
yield key
def keys(self):
for key in self.order:
if key in self:
yield key
def values(self):
for key in self.order:
if key in self:
yield self[key]
def items(self):
for key in self.order:
if key in self:
yield key, self[key]
There is a test:
d = MyDict({"b" : 2, "c": 3, "a": 1}, order=["a","b","c"])
print(d)
for k in d:
print(k, end=" ")
#a b c
print()
for k in d.keys():
print(k, end=" ")
#a b c
print()
for v in d.values():
print(v, end=" ")
#1 2 3
print()
for k, v in d.items():
print(f"{k}-{v}", end=" ")
#a-1 b-2 c-3
You can override __repr__
and __str__
if you want your dictionary to be converted in string (and printed) in the order you want, too