简体   繁体   中英

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

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']

I think pandas might be clearer, but this should work:

# get min length list in `data`
n = min(len(v) for v in data.values())

# get max value for each element in data
result = [max((k for k, v in data.items()), key=lambda x: data[x][j]) for j in range(n)]

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