返回带有排除项的嵌套python词典的最小键值对?

时间:2014-07-06 23:42:27

标签: python dictionary nested minimum

假设我有以下嵌套字典d:

 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:

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]

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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]