2014-07-06 24 views
-1

比方說,我有如下嵌套的字典d:返回帶排除項的嵌套python字典的最小鍵值對嗎?

d = {'1':{'80':982, '170':2620, '2':522}, 
'2':{'42':1689, '127':9365}, 
'3':{'57':1239, '101':3381, '43':7313, '41':7212}, 
'4':{'162':3924} } 

和陣列電:

e = ['2', '25', '56'] 

我想提取在d,而每個條目的鍵值對的最小值排除數組e中的所有鍵。因此,例如,d ['1']中的最小鍵 - 值對是'2':522,但由於'2'在數組e中,我想忽略這個元素並找到最小价值的關鍵不在e。所以對於d ['1'],正確的答案是'80':982。我想爲d中的所有條目執行此操作。輸出應該是這種格式

['1', '80', 982, '2', '42', 1689 ...etc] 
+1

聽起來像是你有到位的要求,現在就開始工作的數組... :) – alfasin

+0

爲什麼是'「80」,982'最低鍵,數值對在字典'1'? '2':522'會比較小... – dawg

回答

0
d = {'1':{'80':982, '170':2620, '2':522}, '2':{'42':1689, '127':9365}, '3':{'57':1239, '101':3381, '43':7313, '41':7212}, '4':{'162':3924} } 

e = ['2', '25', '56'] 
output = {} 

for key in d: 

    innerObj = d[key] 
    tempList = [] 
    for innerKey in innerObj: 
     if e.count(innerKey) > 0: 
     continue 
     else: 
     tempList.append([int(innerKey),innerObj[innerKey]]) 
    tempList.sort() 
    output[key] = {str(tempList[0][0]):tempList[0][1]} 

print output 
0
final=[] 
for k,v in d.iteritems(): 
    s = [ x for x in sorted(v,key= v.get) if x not in e] 
    final += ([k,s[0],v.get(s[0])]) 

print final 
['1', '80', 982, '3', '57', 1239, '2', '42', 1689, '4', '162', 3924]