In Python, How can I get the next and previous key:value of a particular key in a dictionary?

前端 未结 9 1426
栀梦
栀梦 2021-02-05 05:21

Okay, so this is a little hard to explain, but here goes:

I have a dictionary, which I\'m adding content to. The content is a hashed username (key) with an IP address (v

9条回答
  •  遇见更好的自我
    2021-02-05 05:47

    Maybe it is an overkill, but you can keep Track of the Keys inserted with a Helper Class and according to that list, you can retrieve the Key for Previous or Next. Just don't forget to check for border conditions, if the objects is already first or last element. This way, you will not need to always resort the ordered list or search for the element.

    from collections import OrderedDict
    
    class Helper(object):
        """Helper Class for Keeping track of Insert Order"""
        def __init__(self, arg):
            super(Helper, self).__init__()
    
        dictContainer = dict()
        ordering = list()
    
        @staticmethod
        def addItem(dictItem):
            for key,value in dictItem.iteritems():
                print key,value
                Helper.ordering.append(key)
                Helper.dictContainer[key] = value
    
        @staticmethod
        def getPrevious(key):
            index = (Helper.ordering.index(key)-1)
            return Helper.dictContainer[Helper.ordering[index]]
    
    
    #Your unordered dictionary
    d = {'aaaa': 'a', 'bbbb':'b', 'cccc':'c', 'ffffdd':'d', 'eeee':'e', 'ffff':'f'}
    
    #Create Order over keys
    ordered = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
    
    #Push your ordered list to your Helper class
    Helper.addItem(ordered)
    
    
    #Get Previous of    
    print Helper.getPrevious('eeee')
    >>> d
    

提交回复
热议问题