Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get longest element in Dict

I store data in dictionary, where key is an integer, and value is a tuple of integers. I need to get the length of the longest element, and its key.

I found this for getting the max value over dict:

def GetMaxFlow(flows):        
    maks=max(flows, key=flows.get)
    return flows[maks],maks

I tried to modify and as a key use the len function, but it didn't work, so I tried something reasonable and straightforward, yet inefficient:

def GetMaxFlow(flows):
    Lens={}
    for a in flows.iteritems():
        Lens[a[0]]=len(a[1])
    maks=max(Lens, key=Lens.get)
    return Lens[maks],maks

Is there a more elegant, and pythonic way to do it?

like image 864
Intelligent-Infrastructure Avatar asked Feb 14 '12 17:02

Intelligent-Infrastructure


2 Answers

If you need the length and the key:

def GetMaxFlox(flows):
    return max((len(v), k) for k,v in flows.iteritems())

If you need the value and the key:

def GetMaxFlox(flows):
    return max((len(v), v, k) for k, v in flows.iteritems())[1:]

or

def GetMaxFlox(flows):
    return max(((v, k) for k, v in flows.iteritems()), key=lambda (v,k): len(v))
like image 116
eumiro Avatar answered Nov 05 '22 23:11

eumiro


This is one of the reasons lambda still exists in Python I think.

def GetMaxFlow(flows):        
    maks=max(flows, key=lambda k: len(flows[k]))
    return flows[maks],maks

To specifically return a len...

def GetMaxFlow(flows):        
    maks=max(flows, key=lambda k: len(flows[k]))
    return len(flows[maks]), maks

Or use eumiro's solution, which actually makes more sense in this case. (I misunderstood your question.)

like image 43
senderle Avatar answered Nov 05 '22 23:11

senderle