-2
我有一本字典一樣如下:查找下一個和每個字典項先前的元素
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’]
}
我使用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'])
的'dict'類型不排序所以這是行不通的。你的意思是OrderedDict? – RobertB
你的意思是'next'和'previous'是如何將項目最初插入字典或整數鍵的值?在你的例子中它們是相同的,但答案會有所不同。 –
......或甚至「iteritems()返回的順序是什麼?」 –