简体   繁体   中英

How to print the key of highest value from the list's element of the dictionary?

I am still new to python so apologies in advance if my question is confusing. I have this

A  :  [5, 1, 0, 0, 5, 5, 0]
C  :  [0, 1, 1, 2, 1, 0, 2]
G  :  [0, 3, 2, 1, 0, 1, 2]
T  :  [1, 0, 2, 0, 0, 0, 1]

dictionary. I want to print the key of the highest value from the list. For eg:- From the first element of the list ie 5,0,0,1 A has the highest value i want to print A, then for second position its G and so on.

Thank you.

Edited: - Hey guys thank you for all your advice I was able to complete the task.

You can use the following:

d = {"A": [5, 1, 0, 0, 5, 5, 0],
     "C": [0, 1, 1, 2, 1, 0, 2],
     "G": [0, 3, 2, 1, 0, 1, 2],
     "T": [1, 0, 2, 0, 0, 0, 1]}

maxes = [max(d, key=lambda k: d[k][i]) for i in range(len(list(d.values())[0]))]
# ['A', 'G', 'G', 'C', 'A', 'A', 'C']

Assuming you data is in a dictionary (and it's named d ), you can try:

maxkey = max(d.items(), key=lambda x: max(x[1]))[0]
print(maxkey)

Output:

A

Something like this:

>>> def f(di, index):
...     max = None
...     for key in di:
...             if index >= len(di[key]):
...                     continue
...             if max is None or di[max][index] < di[key][index]:
...                     max = key
...     return max
>>> di = {'A': [5, 1, 0, 0, 5, 5, 0],
... 'B': [0, 1, 1, 2, 1, 0, 2]}
>>> f(di, 0)
'A'
>>> f(di, 3)
'B'

For each index (0 to 6) get the key that has the maximum value at that index. That can be done in a list comprehension:

[ max(d,key=lambda k:d[k][i]) for i in range(7)] 

['A', 'G', 'G', 'C', 'A', 'A', 'C']

If you have different lists sizes in your dictionary or you don't know the length of the lists in advance, you can get it first using the min function:

minLen     = min(map(len,d.values()))
maxLetters = [ max(d,key=lambda k:d[k][i]) for i in range(minLen)]

you need to use min() in order to make sure d[k][i] will not go beyond the size of the shortest list.

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