'How to return values in dictionary?

def consensus(seqs):    
>>> profiel(seqs)
    {'A': [0, 3, 1, 2, 3, 4, 0, 3], 'C': [0, 4, 3, 1, 0, 0, 5, 1], 'T': [3, 0, 1, 2, 4, 3, 1, 1], 'G': [4, 0, 2, 2, 0, 0, 1, 2]}
>>> consensus(profiel(seqs))
    'GCCNTACA'

How can I return the key of the dictionary when it have the highest number in the list? So the first one is a G because

A = 0 , C = 0, T = 3, G = 4

And so on.



Solution 1:[1]

def return_max(dic): 
    maxnum = max(i[0] for i in dic.values())        
    for i in dic.iteritems():
        if maxnum == i[1][0]:
            return i[0]

dic = {'A': [0, 3, 1, 2, 3, 4, 0, 3], 'C': [0, 4, 3, 1, 0, 0, 5, 1], 'T': [3, 0, 1, 2, 4, 3, 1, 1], 'G': [4, 0, 2, 2, 0, 0, 1, 2]}
print return_max(dic)

Output:

G

Solution 2:[2]

This will do the job, key of the list with the highest value on it:

mydict = {'A': [0, 3, 1, 2, 3, 4, 0, 3], 'C': [0, 4, 3, 1, 0, 0, 5, 1], 'T': [3, 0, 1, 2, 4, 3, 1, 1], 'G': [4, 0, 2, 2, 0, 0, 1, 2]}

def getKeyBigger(d);
    key,_ = reduce(lambda x, y: x if max(x[1]) > max(y[1]) else y, d.items())
    return key

>>>print getKeyBigger(mydict)
>>>C

Solution 3:[3]

Based on zetsys solution, here's a (ugly) one liner:

"".join([max(d, key={k: v[x] for k, v in d.items()}.get) for x in xrange(len(d.values()[0]))]

It makes the assumption that every list has the same length. (and d is your input dictionary)

Solution 4:[4]

To select key with max value, use this

max(dict, key=dict.get)  

Example:

item = d[d.keys()[0]]

''.join(
    max(d, key=lambda key: d.get(key)[i]) for i in range(len(item))
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Avión
Solution 2
Solution 3 ohe
Solution 4