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?
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))
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With