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

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

    Another way that seems simple and straight forward: this function returns the key which is offset positions away from k

    def get_shifted_key(d:dict, k:str, offset:int) -> str:
        l = list(d.keys())
        if k in l:
            i = l.index(k) + offset
            if 0 <= i < len(l):
                return l[i]
        return None    
    

提交回复
热议问题