【问题标题】:Get max values in a nested dictionary returning with the keys在返回键的嵌套字典中获取最大值
【发布时间】:2022-12-18 07:49:31
【问题描述】:
我是 Python 新手,需要一些帮助。
我有这个嵌套字典:
diccionario = {
"maria": {"valor1": 1, "valor2": 2}
}
我想从嵌套字典中提取最大值。我想要这个回报:{“maria”:valor2}
我写了这个:
res = {clave: {clave: max(val.values())} for clave, val in diccionario.items()}
print (res)
但是返回的是:{'maria': {'maria': 2}}
我试过了:
res = {clave: {clave: max(val.values())} for clave, val in diccionario.items()}
print (res)
返回 --> {'maria': {'maria': 2}}
我想:
{'maria': 'valor2'}
【问题讨论】:
标签:
python
dictionary
nested
【解决方案1】:
你想要的钥匙的最大值,所以让我们这样做。首先,让我们在常规循环中执行此操作。将其浓缩为理解可能会在以后发生。
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]
其中给出了以下res:
{'maria': 'valor2'}
作为字典理解:
res = {key: max(values_dict.items(), key=lambda kvp: kvp[1])[0] for key, values_dict in diccionario.items()}