3 回答
TA贡献1815条经验 获得超13个赞
您可以反转键和值,然后获取具有最小值的键:
a = {0: {0: 7, 1: 2, 2: 5}, 1: {0: 3, 1: 10, 2: 10}}
dict(zip(a[0].values(),a[0].keys())).get(min(a[0].values()))
在这里,我们创建了一个新字典,其键和值与原始字典相反。例如
dict(zip(a[0].values(),a[0].keys()))
Out[1575]: {7: 0, 2: 1, 5: 2}
然后从这里,我们获得原始字典中的最小值,并将其用作此反向字典中的键
编辑
如注释中所示,可以简单地key在min函数内使用:
min(a[0],key = a[0].get)
TA贡献2080条经验 获得超4个赞
import random
def find_min(d, fixed_key):
# Given a dictionary of dictionaries d, and a fixed_key, get the dictionary associated with the key
myDict = d[fixed_key]
# treat the dictionary keys as a list
# get the index of the minimum value, then use it to get the key
sub_key = list(myDict.keys())[myDict.values().index(min(myDict.values()))]
return sub_key
dict1 = {0: {0: 7, 1: 2, 2: 5}, 1: {0: 3, 1: 10, 2: 10}}
print dict1
print find_min(dict1, 0)
添加回答
举报