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'}
CodePudding user response:
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()}
CodePudding user response:
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()}