Python 查找每个字典项的下一个和上一个元素
我有一本字典如下:Python 查找每个字典项的下一个和上一个元素,python,dictionary,Python,Dictionary,我有一本字典如下: d = { 1: [‘a’,’b’], 2: [‘c’,’d’], 8: [‘l’,’p’], 12: [‘u’,’v’,’w’,’x’] } 我正在使用iteritems()迭代字典。如何在迭代时为字典中的每个项目找到上一个和下一个项目?要实现这一点,必须将键转换为列表并依赖于获得的顺序: d = { 1: ['a','b'], 2: ['c','d'], 8: ['l','p'], 12: ['u','v','w','x'] } def
d = {
1: [‘a’,’b’],
2: [‘c’,’d’],
8: [‘l’,’p’],
12: [‘u’,’v’,’w’,’x’]
}
我正在使用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)
dict
类型未订购,因此无法使用。您是指OrderedDict吗?您是指“下一步”和“上一步”,如项目最初插入dict的方式,还是整数键的值?在你的例子中,它们是相同的,但答案会有所不同。。。。或者,即使在“iteritems()返回的顺序是什么?”中,您可能在尝试执行任何操作时使用了错误的数据结构。这是一个有序字典。对于键值对2:['c','d'],下一项将是8:['l','p'],上一项将是1:['a','b']
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'])