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

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

    You can store the keys and values in temp variable in prior, and can access previous and next key,value pair using index.

    It is pretty dynamic, will work for any key you query. Please check this code :

    d = {'1234': '8.8.8.8', '2345':'0.0.0.0', '3213':'4.4.4.4', '4523':'1.1.1.1', '7654':'1.3.3.7', '9999':'127.0.0.1'}
    ch = raw_input('Pleasure Enter your choice : ')
    keys = d.keys()
    values = d.values()
    #print keys, values
    for k,v in d.iteritems():
        if k == ch:
            ind = d.keys().index(k)
            print keys[ind-1], ':',values[ind-1]
            print keys[ind+1], ':',values[ind+1]
    

提交回复
热议问题