简体   繁体   中英

Pythonic Way of Lexicographically Sorting Keys of an OrderedDict On Insert

I have the following class that keeps track of an OrderedDict :

class LexDict:
    def __init__(self):
        self.m_map = OrderedDict() # maps string which is case-sensitive to int

    def set(self,id,seqNo):
        self.m_map[id] = seqNo

    def get(self,id): # seqNo returned
        return self.m_map[id] if self.has(id) else 0

    def has(self,id): # bool value
        return ( id in self.m_map.keys() )

    def to_str(self):
        stream = ""
        for key,value in self.m_map.items():
            stream = stream + key + ":" + str(value) + " "
        return stream.rstrip()

My goal is to change the set() method to make it lexicographic at all times so that no matter when to_str() is called, it will be in lexicographic order. We can safely assume no mapping in this dictionary will be removed. This will be used in a network situation so efficiency is key and sorting the entire list rather than moving it in the correct spot would hurt performance.

An example of how this could be used.

a = LexDict()

a.set("/Justin",1) # the id will have "/"s (maybe even many) in it, we can image them without "/"s for sorting

a.set("/James",600)

a.set("/Austin",-123)
print( a.to_str() )

Output /Austin:-123 /James:600 /Justin:1

I am a little confused. It sounds like you are referring to the OrderedDict class from the sortedcollections module; that module also contains what you are looking for, namely a SortedDict. In general, the sortedcollections module contains many containers for efficiently using large lists and dictionaries. For example, look up time in a SortedDict is O(log(n)) instead of O(n) for normal python dict().

from sortedcollections import SortedDict

D = SortedDict([("/James",600),("/Justin",1),("/Austin",-123)])
print(D)

In general, SortedDict and SortedList can hold millions of values, but instantly look up values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM