How can I find the maximum value from within the nested dictionaries and return this value with the key from the nested dictionary and the key from the 'main' dictionary (sorry, dont know the correct terminology for the outer dictionary)? For example, if I have the following:
my_dict = {
0: {1: 10, 2: 20, 3: 30},
10: {10: 100, 20: 200, 30: 300},
20: {100: 1000, 200: 2000, 300: 3000}
}
The maximum value is 3000
which has the key 300
and this belongs to the 'main' key 20
. How can I return this value and its two associated keys?
CodePudding user response:
Here's an option with comprehension and max
:
my_dict = {
0: {1: 10, 2: 20, 3: 30},
10: {10: 100, 20: 200, 30: 300},
20: {100: 1000, 200: 2000, 300: 3000}
}
m = max({max(d.values()) for d in my_dict.values()})
For getting the keys as well:
my_dict = {
0: {1: 10, 2: 20, 3: 30},
10: {10: 100, 20: 200, 30: 300},
20: {100: 1000, 200: 2000, 300: 3000}
}
def get_max_key_value(d):
max_key = max(d, key=d.get)
return max_key, d[max_key]
max_values = {k: get_max_key_value(inner_dict) for k, inner_dict in my_dict.items()}
print(get_max_key_value(max_values))
Which yields:
(20, (300, 3000))
CodePudding user response:
You can do that in 2 steps, first you find the nested dictionary which has the maximum number in it's values :
my_dict = {
0: {1: 10, 2: 20, 3: 30},
10: {10: 100, 20: 200, 30: 300},
20: {100: 1000, 200: 2000, 300: 3000},
}
# step 1
k_outer, v_outer = max(my_dict.items(), key=lambda x: max(x[1]))
# step 2
k_inner, v_inner = max(v_outer.items(), key=lambda x: x[1])
print(k_outer, k_inner, v_inner)
output:
20 300 3000
I believe the above solution will work quite efficiently but you can find the items you're interested in, in just one iteration as well:
my_dict = {
0: {1: 10, 2: 20, 3: 30},
10: {10: 100, 20: 200, 30: 300},
20: {100: 1000, 200: 2000, 300: 3000},
}
max_value = float("-inf")
outer_key = None
inner_key = None
for k_outer, v_outer in my_dict.items():
for k_inner, v_inner in v_outer.items():
if v_inner > max_value:
max_value = v_inner
outer_key = k_outer
inner_key = k_inner
print(outer_key, inner_key, max_value)
This way whenever you find a value (v_inner
) that is bigger that your max_value
, you store those two keys (outer_key
, inner_key
). After the iteration completes, you have your data.