Custom Create ordered dictionary classes
Dict's __getitem__ method is somewhat different and wants to use a custom __getitem__ method to display the subscript of the query key;
#/usr/bin/env python3#-*-coding:utf-8-*-# author:zshaoxclass mydict (dict): li = [] #定义列表用于有序的排列key值 def __setitem__ (self, Key, value): #自定义__setitem__方法, extending the parent class method Self.li.append (key) #将对象的key added to the list super (mydict, SE LF). __setitem__ (key, value) #将key, value is written to the dictionary, calling the parent class __setitem__ method def __str__ (self): #自定义__str__方法 Temp_ List = [] #定义临时列表 the dictionary string used to hold the stitching for key in Self.li: value = Self.get (key) if type (value) = = Int: msg = "'%s ':%s"% (key, value) temp_list.append (msg) elif type (value) = = str: msg = "'%s ': '%s '"% (key, value)
temp_list.append (msg) temp_str = ' {' + ', '. Join (Temp_list) + '} ' #拼接字典字符串 return temp_strdic = Mydict () dic[' k1 '] = 123dic[' K2 '] = 321print (dic, type (DIC)) print (DIC)
Python Learning ordered Dictionaries