简体   繁体   English

Python:获取字典中值最小但具有多个最小值的键

[英]Python: get key with the least value from a dictionary BUT multiple minimum values

I'm trying to do the same as Get the key corresponding to the minimum value within a dictionary , where we want to get the key corresponding to the minimum value in a dictionary. 我正在尝试执行与获取与字典中的最小值对应的键相同的操作,其中我们希望获得与字典中的最小值对应的键。

The best way appears to be: 最好的方式似乎是:

min(d, key=d.get)

BUT I want to apply this on a dictionary with multiple minimum values: 但是我想在具有多个最小值的字典上应用它:

d = {'a' : 1, 'b' : 2, 'c' : 1}

Note that the answer from the above would be: 请注意,上面的答案是:

>>> min(d, key=d.get)
'a'

However, I need both the two keys that have a minimum value, namely a and c . 但是,我需要两个具有最小值的键,即ac

What would be the best approach? 什么是最好的方法?

(Ultimately I want to pick one of the two at random, but I don't think this is relevant). (最终我想随机选择其中一个,但我不认为这是相关的)。

One simple option is to first determine the minimum value, and then select all keys mapping to that minimum: 一个简单的选择是首先确定最小值,然后选择映射到该最小值的所有键:

min_value = min(d.itervalues())
min_keys = [k for k in d if d[k] == min_value]

For Python 3 use d.values() instead of d.itervalues() . 对于Python 3,使用d.values()而不是d.itervalues()

This needs two passes through the dictionary, but should be one of the fastest options to do this anyway. 这需要两次通过字典,但无论如何应该是最快的选项之一。

Using reservoir sampling , you can implement a single pass approach that selects one of the items at random: 使用油藏采样 ,您可以实施单通道方法,随机选择其中一个项目:

it = d.iteritems()
min_key, min_value = next(it)
num_mins = 1
for k, v in it:
    if v < min_value:
        num_mins = 1
        min_key, min_value = k, v
    elif v == min_value:
        num_mins += 1
        if random.randrange(num_mins) == 0:
            min_key = k

After writing down this code, I think this option is of rather theoretical interest… :) 在写下这段代码之后,我认为这个选项具有相当的理论意义...... :)

EDITED: Now using setdefault as suggested :) 编辑:现在使用setdefault建议:)

I don't know if that helps you but you could build a reverse dictionary with the values as key and the keys (in a list as values). 我不知道这是否对你有所帮助,但你可以构建一个反向字典,其值为键和键(在列表中作为值)。

d = {'a' : 1, 'b' : 2, 'c' : 1}
d2 = {}
for k, v in d.iteritems():
    d2.setdefault(v, []).append(k)
print d2[min(d2)]

It will print this: 它会打印出来:

['a', 'c']

However, I think the other solutions are more compact and probably more elegant... 但是,我认为其他解决方案更紧凑,可能更优雅......

min_keys = [k for k in d if all(d[m] >= d[k] for m in d)]

or, slightly optimized 或者,略微优化

min_keys = [k for k, x in d.items() if not any(y < x for y in d.values())]

It's not as efficient as other solutions, but demonstrates the beauty of python (well, to me at least). 它不如其他解决方案有效,但展示了python的美丽(至少对我而言)。

def get_rand_min(d):
    min_val = min(d.values())
    min_keys = filter(lambda k: d[k] == min_val, d)
    return random.choice(min_keys)

You can use heapq.nsmallest to get the N smallest members of the dict, then filter out all that are not equal to the lowest one. 您可以使用heapq.nsmallest来获取dict的N个最小成员,然后过滤掉所有不等于最低成员的成员。 That's provided you know the maximal number of smallest members you can have, let's assume it's N here. 这让你知道你可以拥有的最小成员的最大数量,让我们假设它在这里是N. something like: 就像是:

from heapq import nsmallest
from operator import itemgetter

#get the N smallest members
smallestN = nsmallest(N, myDict.iteritems(), itemgetter(1)))

#leave in only the ones with a score equal to the smallest one
smallest = [x for x in smallestN if x[1] == smallestN[0][1]]

This works: 这有效:

d = {'a' :1, 'b' : 2, 'c' : 1}
min_value = min(d.values())
result = [x[0] for x in d.items() if x[1] == k]

Hmpf. 哼。 After fixing up the code to work, I ended up with @Sven Marnach's answer, so, disregard this ;) 在修复代码工作之后,我最终得到了@Sven Marnach的答案,所以,请忽略这一点;)

minValue,minKey = min((v,k) for k,v in d.items())

Due to your semantics you need to go through the entire dictionary at least once. 由于您的语义,您需要至少完成一次整个字典。 This will retrieve exactly 1 minimum element. 这将精确检索1个最小元素。

If you want all the minimum items in O(log(N)) query time, you can insert your elements into a priority queue as you generate them (if you can). 如果您想要O(log(N))查询时间中的所有最小项目,您可以在生成它们时将元素插入优先级队列(如果可以)。 The priority queue must have O(1) insertion time and O(log(N)) extract-min time. 优先级队列必须具有O(1)插入时间和O(log(N))提取最小时间。 (This will be as bad as sorting if all your elements have the same value, but otherwise may work quite well.) (如果您的所有元素都具有相同的值,那么这将与排序一样糟糕,但在其他情况下也可以正常工作。)

Here's another way to do it in one pass: 这是另一种通过一次传递的方式:

d = {'foo': 2, 'a' : 1, 'b' : 2, 'c' : 1, 'z': 99, 'x': 1}
current_min = d[d.keys()[0]]
min_keys = []
for k, v in d.iteritems():
    if v < current_min:
        current_min = v
        min_keys = [k]
    elif v == current_min:
        min_keys.append(k)
print min_keys
['a', 'x', 'c']

One pass solution would be: 一遍解决方案是:

 >>> result = [100000, []]
>>> for key, val in d.items():
...  if val < result[0]:
...   result[1] = [key]; result[0]=val;
...  elif val == result[0]:
...   result[1].append(key)
... 
>>> result
[1, ['a', 'c']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查找字典python中值最小的键,由字符串格式的值组成 - find key with least value in dictionary python consisting of values in string format 具有双值键的Python字典,需要查找最大值和最小值 - Python Dictionary with dual values key, need to find maximum and minimum value 在包含“无”/“假”值的字典上获取具有最小值的键 - Get key with minimum value on a dictionary that contains 'None' / 'False' values 从具有多个值 Python 字典的每个键中获取具有最大计数的值 - Get value with max count from each key with multiple values Python dictionary Python如何从具有多个值的字典键中删除特定值? - Python how to delete a specific value from a dictionary key with multiple values? 需要从具有多个值的字典键返回单个值 (Python) - Need to Return a Single Value from a Dictionary Key with Multiple Values (Python) 具有多个值的键-检查值是否在字典python中 - Key with multiple values - check if value is in dictionary python 获取字典中3个最小值对应的key - Get the key corresponding to the 3 minimum values within a dictionary 如何在python中为具有多个值的字典查找带有值的字典键? - How to find key of dictionary with from values for a dictionary with multiple values in python? Python字典获得“属性”值最小的值 - Python dictionary get the value with the least 'attribute' value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM