Python Learning ordered Dictionaries

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.