Festlandtommy
Festlandtommy

Reputation: 112

Finding max in Python dict with nested tuple keys

Say I have this Python dict:

dict = {
((0,0), 'A'): 0.0, 
((0,0), 'B'): 0.7,
...
((2,4), 'C'): 0.2,
...}

I want to find the maximum value for a given nested tuple like (0,0). Something like:

max(dict((0,0), *). 

In this case it should return 0.7, how to do this?

Upvotes: 0

Views: 269

Answers (3)

Jorge Martinez Ortega
Jorge Martinez Ortega

Reputation: 51

I did a very simple example of your question. Surely there is a more efficient way to do it.

dict = { ((0, 0), "A"): 0.0,
         ((0, 0), "B"): 0.7, 
         ((0, 0), "C"): 0.9, 
         ((0, 1), "A"): 0.0,
         ((0, 1), "B"): 0.7, 
         ((0, 1), "C"): 0.8}
mymax={}
for key1,key2 in dict:
    if key1 in mymax:
        mymax[key1] = max(mymax[key1],dict[(key1,key2)])
    else:
         mymax[key1] = dict[(key1,key2)]

mymax= {(0, 0): 0.9, (0, 1): 0.8} has the maximum of every kind.

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

If i understood you you need.

d = {((0,0), 'A'): 0.0, ((0,0), 'B'): 0.7, ((2,4), 'C'): 0.2,}
dValue = dict((k, v) for k,v in d.items() if k[0] == (0,0))
print( max(dValue.values()) )

Output:

0.7

Upvotes: 1

jpp
jpp

Reputation: 164653

Using collections.defaultdict followed by a dictionary comprehension:

d = {((0,0), 'A'): 0.0, 
     ((0,0), 'B'): 0.7,
     ((2,4), 'C'): 0.2}

from collections import defaultdict

res = defaultdict(list)

for (k1, k2), v in d.items():
    res[k1].append(v)

max_vals = {k: max(v) for k, v in res.items()}

print(max_vals)

{(0, 0): 0.7, (2, 4): 0.2}

Upvotes: 2

Related Questions