-1

Let's say I have the following nested dictionary 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} } 

and an array e:

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

I want to extract the minimum value of the key-value pairs in each entry in d while excluding all keys in array e.

So, for example, the smallest key-value pair in d['1'] is '2':522, but since '2' is in array e, I would like to ignore this element and find the smallest value whose key is not in e. So for d['1'] the correct answer would be '80':982. I want to do this for all entries in d. The output should be an array with this format

['1', '80', 982, '2', '42', 1689 ...etc]
user3809888
  • 377
  • 1
  • 6
  • 23

2 Answers2

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
jwodder
  • 54,758
  • 12
  • 108
  • 124
gtaank
  • 21
  • 2
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]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321