简体   繁体   English

Python-获取元组字典中特定元组索引最小值的键

[英]Python - Get key of specific tuple index minimum in dictionary of tuples

I have a dict of tuples such as: 我有一个元组的字典,例如:

d = {'a': (3, 5), 'b': (5, 8), 'c': (9, 3)}  

I want to return the key of the minimum of the tuple values based on the tuple index. 我想返回基于元组索引的最小元组值的键。 For example, if using tuple index = 0, then 'a' would be returned. 例如,如果使用元组索引= 0,则将返回'a'。 if index = 1, then 'c' would be returned. 如果index = 1,则将返回'c'。 I have tried using min(), for example 例如,我尝试使用min()

min(d, key=d.get)

but am not sure how to manipulate it to select the tuple index to use. 但不确定如何操纵它以选择要使用的元组索引。 Although there are similar questions, I have not found an answer to this. 尽管存在类似的问题,但我尚未找到答案。 Apologies in advance if this is a duped question, and please link to the answer. 如果这是一个假问题,请提前致歉,请链接到答案。 Thanks 谢谢

You can write a lambda function to get the elements from the value by their index: 您可以编写一个lambda函数,以通过索引从值中获取元素:

min(d, key=lambda k: d[k][0])
# 'a'
min(d, key=lambda k: d[k][1])
# 'c'

Since multiple keys could have the same value, you might want to return a list of matching keys, not just a single key. 由于多个键可能具有相同的值,因此您可能希望返回匹配键的列表,而不仅仅是单个键。

def min_keys(d, index):

    # Initialize lists
    values = []
    matches = []

    # Append tuple items to list based on index
    for t in list(d.values()):
        values.append(t[index])

    # If the item matches the min, append the key to list
    for key in d:
        if d[key][index] == min(values):
            matches.append(key)

    # Return a list of all keys with min value at index
    return matches

Dictionaries are unsorted and have no index. 字典未排序,没有索引。

If you want the return the key alphabetically first you could use the ascii order: 如果要先按字母顺序返回键,则可以使用ascii顺序:

print(chr(min([ord(key) for key in d.keys()])))

Here's a portable method you can use for dicts with a structure like yours, and feel free to choose the index of interest in the tuple: 这是一种可移植的方法,可用于具有类似您的结构的字典,并可以在元组中随意选择感兴趣的索引:

def extract_min_key_by_index(cache, index):
    min_val = float('inf')
    min_key = 0

    for k, v in d.iteritems():
        if v[index] < min_val:
            min_key, min_val = k, v[index]

    return min_key


d = {'a': (3, 5), 'b': (5, 8), 'c': (9, 3)}
INDEX = 0

print extract_min_key_by_index(d, INDEX)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM