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

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

    You could also use the list.index() method.

    This function is more generic (you can check positions +n and -n), it will catch attempts at searching a key that's not in the dict, and it will also return None if there's nothing before of after the key:

    def keyshift(dictionary, key, diff):
        if key in dictionary:
            token = object()
            keys = [token]*(diff*-1) + sorted(dictionary) + [token]*diff
            newkey = keys[keys.index(key)+diff]
            if newkey is token:
                print None
            else:
                print {newkey: dictionary[newkey]}
        else:
            print 'Key not found'
    
    
    keyshift(d, 'bbbb', -1)
    keyshift(d, 'eeee', +1)
    

提交回复
热议问题