如何在嵌套字典中找到最小值的键?

时间:2018-08-14 17:09:50

标签: python python-3.x numpy

我有以下代码可生成嵌套字典。

import random
import numpy as np

dict1 = {}
for i in range(0,2):
    dict2 = {}
    for j in range(0,3):
        dict2[j] = random.randint(1,10)
    dict1[i] = dict2

例如,它可以生成dict1的以下内容:

{0: {0: 7, 1: 2, 2: 5}, 1: {0: 3, 1: 10, 2: 10}}

我想找到固定键最小值的子键。例如,对于固定键0,嵌套字典值中的最小值是2,它引用了w子键1。因此结果应为1

result=find_min(dict1[0])
result
1

如何开发此类find_min函数?

4 个答案:

答案 0 :(得分:5)

您可以反转键和值,然后获取具有最小值的键:

 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)

答案 1 :(得分:2)

要提取键0的子字典,只需执行以下操作:

sub_dict = dict1[0]

然后,找到对应于最小值的键:

min_value, min_key = min((value, key) for key, value in sub_dict.items())

答案 2 :(得分:-1)

这是最快的方法

def find_min(dic):
    mini = float('inf')  # mini is init with +inf value
    for key, value in dic.items():  # iterate over keys and values in dic
        if value < mini:  # if new min found
            key_of_min_value = key   # update key
            mini = value  # update min
    return key_of_min_value

答案 3 :(得分:-1)

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)