Python中自定义有序字典

1
2
3
4
5
6
7
8
9
10
class MyDict(dict):
def __init__(self):
super(MyDict, self).__init__()
self.li = []

md = MyDict()
md["k1"] = 123
md["k2"] = 456

print(md)

在不破坏字典对象构造方法的情况下,自定义创建一个列表,用来存放key

1
2
3
4
5
6
7
8
class MyDict(dict):
def __init__(self):
super(MyDict, self).__init__()
self.li = []

def __setitem__(self, key, value):
self.li.append(key)
super(MyDict, self).__setitem__(key, value)

将新的键值对保存到字典的时候,保存它的key到我们自定义创建的列表中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class MyDict(dict):
def __init__(self):
super(MyDict, self).__init__()
self.li = []

def __setitem__(self, key, value):
self.li.append(key)
super(MyDict, self).__setitem__(key, value)

def __str__(self):
tmp_list = []
for key in self.li:
value = self.get(key) # 使用了父类的get方法
tmp_list.append("'%s': %s" % (key, value))
tmp_str = "{" + ", ".join(tmp_list) + "}"
return tmp_str

md = MyDict()
md["k1"] = 123
md["k2"] = 456

print(md)

------------

{'k1': 123, 'k2': 456}