0

我想遍历字典的子集以找到子集中的最小值。我可以使用生成器表达式来获取值:

>>> S = {'a', 'c'}
>>> D = {'a': 2, 'b': 0, 'c': 1, 'd': 3}
>>> min(D[k] for k in S)
1

要获取关联的密钥,我想这是可能的:

>>> subset_min = min(D[k] for k in S)
>>> [k for k, v in D.iteritems() if v == subset_min]
['c']

但是肯定有一种方法不需要再次搜索字典吗?我希望像这里min(D, key=D.get)讨论的那样,但我看不出在这种情况下如何应用它。

4

2 回答 2

5
min(S, key=D.get)

Surprisingly simple.

于 2013-08-14T19:01:12.983 回答
1
min_val, min_key = min((D[k], k) for k in S)

This will give you a key which is associated with the minimum value, but it will not tell you if there are multiple such keys.

Or, you could find the key first, and then access the associated value:

min_key = min(S, key=D.get)
min_val = D[min_key]

If you want to collect all the keys in D associated with subset_min, then you'll have it iterate over all of D, as you posted.

于 2013-08-14T19:01:51.823 回答