Get max values in a nested dictionary returning with the keys

Question:

I’m new to Python and I need some help.

I have this nested dictionary:

diccionario = {
    "maria": {"valor1": 1, "valor2": 2}
}

And I want to extract the max value from the nested dictionary. I want this return: {"maria": valor2}

I have written this:

res = {clave: {clave: max(val.values())} for clave, val in diccionario.items()}



print (res)

But the return is: {'maria': {'maria': 2}}

I tried:

res = {clave: {clave: max(val.values())} for clave, val in diccionario.items()}

print (res)

return –> {'maria': {'maria': 2}}

I want:

{'maria': 'valor2'}

Asked By: Joana

||

Answers:

You want the key of the maximum value, so let’s do that. First, let’s do it in a regular loop. Condensing it to a comprehension can happen later.

res = {}
for key, values_dict in diccionario.items():
    # Find the max of values_dict.items(). 
    # Each element of this is a tuple representing the key-value pair. 
    # The first element of the tuple is the key, the second is the value
    max_kvp = max(values_dict.items(), 
                  key=lambda kvp: kvp[1]) 
    # the key for max is the second item of the key-value pair (i.e. the value)

    # Now, max_kvp is the key-value pair that has the max value
    # Let's set the KEY of that pair as the value for res[key]
    res[key] = max_kvp[0]

Which gives the following res:

{'maria': 'valor2'}

As a dict comprehension:

# Find the max KVP by value     Take the first element of that KVP
# └----------v                                 └-------------v
res = {key: max(values_dict.items(), key=lambda kvp: kvp[1])[0] 
       for key, values_dict in diccionario.items()}
Answered By: Pranav Hosangadi

You can use the key argument of the max function and set it to the accessor method of the dict:

{key: max(val, key=val.get) for key, val in diccionario.items()}
Answered By: Jab

This might help!

diccionario = {
    "maria": {"valor1": 1, "valor2": 2}
}

p={key: max(zip(value.values(),value.keys()))[1] for key, value in diccionario.items()}
print(p)
Answered By: AlekhyaV – Intel

the others respondants gave fantastic answers so far 🙂

I’d like to point out that when working with comprehensions in Python, the structure of your code is the data you’ll get in a WYSIWYG fashion.

From your code sample:

{clave: {clave: max(val.values())} for clave, val in diccionario.items()}

You can see that the structure this comprehension produces is a dict whose values are dict which in turn have scalar values. Hence the result:

{'maria': {'maria': 2}}

As Pranav suggested, in such cases, it’s easier to prototype code like this using for/while loops before going full-functional with comprehensions.

Another way to do it would be to flatten the nested dict

d1 = {k: tuple(v.items()) for k, v in d.items()}

Sort each value as tuple of pairs key, value

d2 = {k: sorted(v, key=lambda a:a[1], reverse=True) for k, v in d1.items()}

And finally, get the value keyed to the maximum

d3 = {k: v[0][0] for k, v in d2.items()}

Hope this helps.

Answered By: slouchart
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.