简体   繁体   中英

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. if index = 1, then 'c' would be returned. I have tried using min(), for example

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:

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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