我有一个如下字典:
d = {
1: [‘a’,’b’],
2: [‘c’,’d’],
8: [‘l’,’p’],
12: [‘u’,’v’,’w’,’x’]
}
我正在使用iteritems()迭代字典。如何在迭代时找到字典中每个项目的上一个和下一个项目?
答案 0 :(得分:0)
要实现这一点,必须将密钥转换为列表并依赖于获得的订单:
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)
答案 1 :(得分:-1)
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'])