Searching a Python dictionary based on the value first, to get a key output make sense to me. But what if we want to add another constraint to the search?
For instance, here I am searching a dictionary (multi-dimensional) for the lowest value, then returning the key of that lowest value:
minValue[id] = min(data[id].items(), key=lambda x: x[1])
Since this method only returns one key that matches that value, while there may be multiple, I want to add another constraint.
Is there an elegant way to add: return key that contains overall minimum value AND has the longest length of those matching ?
I think a specific example would be helpful to clarify what the dictionary looks like since python doesn’t directly provide a multi-dimensional dict.
I assume that it looks something like this:
data = {'a': 1, 'b': 2, 'b': 3}(note, this is not valid python!), so that what you when you domin(data[id].items(), key=lambda x: x[1])you want it to return('a', 1), and checking for the longest length matching would give, perhaps [(‘b’, 2), (‘b’, 3)].If that is what you mean, then the easiest way is to use a defaultdict with a set: