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

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

    Try:

    pos = 0
    d = {'aaaa': 'a', 'bbbb':'b', 'cccc':'c', 'ffffdd':'d', 'eeee':'e', 'ffff':'f'}
    
    for i in d:
        pos+=1
        if i == 'eeee':
            listForm = list(d.values())
            print(listForm[pos-1])
            print(listForm[pos+1])
    

    As in @AdamKerz's answer enumerate seems pythonic, but if you are a beginner this code might help you understand it in an easy way.

    And I think its faster + smaller compared to sorting followed by building list & then enumerating

提交回复
热议问题