返回带排除项的嵌套Python字典的最小键值对?

-1 投票
2 回答
621 浏览
提问于 2025-04-18 12:18

假设我有一个这样的嵌套字典 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
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]

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

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

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

撰写回答