查找下一个和每个字典项先前的元素

问题描述:

我有一本字典一样如下:查找下一个和每个字典项先前的元素

d = { 
    1: [‘a’,’b’], 
    2: [‘c’,’d’], 
    8: [‘l’,’p’], 
    12: [‘u’,’v’,’w’,’x’] 
} 

我使用iteritems()我怎么能找到一个和下一个项目,通过字典迭代。迭代时字典中的每个项目?

+6

的'dict'类型不排序所以这是行不通的。你的意思是OrderedDict? – RobertB

+1

你的意思是'next'和'previous'是如何将项目最初插入字典或整数键的值?在你的例子中它们是相同的,但答案会有所不同。 –

+1

......或甚至“iteritems()返回的顺序是什么?” –

为了实现这一目标,就必须键转换成一个列表,并依靠所获得的顺序:

d = { 
    1: ['a','b'], 
    2: ['c','d'], 
    8: ['l','p'], 
    12: ['u','v','w','x'] 
} 

def getValBeforeAndAfter(d, the_key): 
    # convert keys into the list 
    d_list = list(sorted(d)) 
    index = None 
    if (the_key in d_list): 
     index = d_list.index(the_key) 
     try: 
      key_before = d_list[index-1] 
      key_after = d_list[index+1] 
      return str(key_before) + ": " + str(d[key_before]) + "\n" + str(key_after) + ": " + str(d[key_after]) 
     except: print "Out of range. You are on the edge of the dictionary"   
    else: 
     return "No such key in dictionary" 

""" 
Small test. Expected output: 
1: ['a', 'b'] 
8: ['l', 'p'] 
""" 
print getValBeforeAndAfter(d, 2) 

from collections import OrderedDict 

d2 = {} 
d2 = OrderedDict(d2) 
d2.update({1: ['a','b']}) 
d2.update({2: ['c','d']}) 
d2.update({8: ['l','p']}) 
d2.update({12: ['u','v','w','x']}) 

def ajacent(di,key): 
    li = list(di.items()) 
    for i, item in enumerate(li): 
     k,v = item 
     if k == key and i > 0: 
      print(li[i-1]) 
      print(item) 
      print(li[i+1]) 


print(ajacent(d2,2)) 

(1, ['a', 'b']) 
(2, ['c', 'd']) 
(8, ['l', 'p'])