Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare lists inside dictionary and get the winning key

i have a dictionary containing the following lists:

data = {'A': [194.0, 78.0, 75.0],
        'H': [74.0, 211.0, 101.0],
        'L': [75.0, 99.0, 111.0],
        'Z': [193.0, 75.0, 74.0],
        'X': [61.0, 124.0, 66.0],
        'Y': [44.0, 81.0, 52.0]}

The number of keys changes, but the number of entries inside each list does not. I need get the key of the row with the biggest number in each column, so I can write a file containing [A,H,L].

I can't think of a way that doesent involve rebuilding the dictionary as a list of lists, or jumping into pandas. I was wondering if there's a pythonic way of solving it the way it is.

Thanks

like image 448
Mauro Avatar asked Jan 23 '26 20:01

Mauro


1 Answers

non-pandas solution:

data = {
    "A": [194.0, 78.0, 75.0],
    "H": [74.0, 211.0, 101.0],
    "L": [75.0, 99.0, 111.0],
    "Z": [193.0, 75.0, 74.0],
    "X": [61.0, 124.0, 66.0],
    "Y": [44.0, 81.0, 52.0],
}

out = [
    max(zip(data.keys(), x), key=lambda k: k[1])[0] for x in zip(*data.values())
]
print(out)

Prints:

['A', 'H', 'L']
like image 162
Andrej Kesely Avatar answered Jan 25 '26 09:01

Andrej Kesely



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!