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

前端 未结 9 1428
栀梦
栀梦 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]
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-02-05 06:06

    As seen in the OrderedDict source code, if you have a key and you want to find the next and prev in O(1) here's how you do that.

    >>> from collections import OrderedDict
    >>> d = OrderedDict([('aaaa', 'a',), ('bbbb', 'b'), ('cccc', 'c'), ('ffffdd', 'd'), ('eeee', 'e'), ('ffff', 'f')])
    >>> i = 'eeee'
    >>> link_prev, link_next, key = d._OrderedDict__map['eeee']
    >>> print 'nextKey: ', link_next[2], 'prevKey: ', link_prev[2]
    nextKey:  ffff prevKey:  ffffdd
    

    This will give you next and prev by insertion order. If you add items in random order then just keep track of your items in sorted order.

    0 讨论(0)
提交回复
热议问题