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

前端 未结 9 1536
栀梦
栀梦 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:45

    I think this is a nice Pythonic way of resolving your problem using a lambda and list comprehension, although it may not be optimal in execution time:

    import collections
    
    x = collections.OrderedDict([('a','v1'),('b','v2'),('c','v3'),('d','v4')])
    
    previousItem = lambda currentKey, thisOrderedDict : [
        list( thisOrderedDict.items() )[ z - 1 ] if (z != 0) else None
        for z in range( len( thisOrderedDict.items() ) )
        if (list( thisOrderedDict.keys() )[ z ] == currentKey) ][ 0 ]
    
    nextItem = lambda currentKey, thisOrderedDict : [
        list( thisOrderedDict.items() )[ z + 1 ] if (z != (len( thisOrderedDict.items() ) - 1)) else None
        for z in range( len( thisOrderedDict.items() ) )
        if (list( thisOrderedDict.keys() )[ z ] == currentKey) ][ 0 ]
    
    assert previousItem('c', x) == ('b', 'v2')
    assert nextItem('c', x) == ('d', 'v4')
    assert previousItem('a', x) is None
    assert nextItem('d',x) is None
    

提交回复
热议问题