Reputation: 105
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
Upvotes: 3
Views: 60
Reputation: 11171
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)]
Upvotes: 0
Reputation: 195418
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']
Upvotes: 4