Get the longest element in a dict

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

I found this to get the maximum value over the dict:

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

I tried to change and use the function as the key len, but this did not work, so I tried something sensible and direct, but ineffective:

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 this?

+5
source share
3 answers

This is one of the reasons why lambdait still exists in Python.

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

To accurately return len ...

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

eumiro , . ( .)

+11

:

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

:

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

def GetMaxFlox(flows):
    return max(((v, k) for k, v in flows.iteritems()), key=lambda (v,k): len(v))
+3

You do not need to save the lengths of all elements, you only need to save the key and the length of the longest tuple:

def GetMaxFlow(flows):
    maks_length=0
    for key,value in flows.iteritems():
            if len(value)>=maks_length:
                    maks_key = key
                    maks_length = len(value)
    return maks_length, maks_key     
0
source

All Articles