Python – 嵌套字典中的最大值
有时,在使用Python字典时,我们可能会遇到每个键本身是具有多个键的记录的问题,我们希望将值替换为字典键的最大值。这种问题可以在涉及数据的许多领域中得到应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们迭代每个键的键以获得最大值并设置在结果字典中。
# Python3 code to demonstrate working of
# Maximum Value in Nested Dictionary
# Using loop
# initializing dictionary
test_dict = {'gfg' : {'a' : 15, 'b' : 14},
'is' : {'d' : 2, 'e' : 10, 'f' : 3},
'best' : {'g' : 19}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Maximum Value in Nested Dictionary
# Using loop
res = {}
for key, val in test_dict.items():
max_val = 0
for ele in val.values():
if ele > max_val:
max_val = ele
res[key] = max_val
# printing result
print("The modified dictionary : " + str(res))
输出 :
The original dictionary is : {‘is’: {‘f’: 3, ‘e’: 10, ‘d’: 2}, ‘gfg’: {‘a’: 15, ‘b’: 14}, ‘best’: {‘g’: 19}}
The modified dictionary : {‘best’: 19, ‘is’: 10, ‘gfg’: 15}
方法 #2:使用max()
+ 字典理解
这是可以执行此任务的另一种方式。在此,我们使用 max() 执行提取最大值的任务,并使用字典理解来迭代和构造新字典。
# Python3 code to demonstrate working of
# Maximum Value in Nested Dictionary
# Using max() + dictionary comprehension
# initializing dictionary
test_dict = {'gfg' : {'a' : 15, 'b' : 14},
'is' : {'d' : 2, 'e' : 10, 'f' : 3},
'best' : {'g' : 19}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Maximum Value in Nested Dictionary
# Using max() + dictionary comprehension
res = {key: max(val.values()) for key, val in test_dict.items()}
# printing result
print("The modified dictionary : " + str(res))
输出 :
The original dictionary is : {‘is’: {‘f’: 3, ‘e’: 10, ‘d’: 2}, ‘gfg’: {‘a’: 15, ‘b’: 14}, ‘best’: {‘g’: 19}}
The modified dictionary : {‘best’: 19, ‘is’: 10, ‘gfg’: 15}