siva
siva

Reputation: 2145

Python: Returning max value of a dict by its tupled-key

I have a dict as follows:

counts = {('test1', 'alpha'): 2, 
          ('test2', 'beta'): 1, 
          ('test1', 'delta'): 1, 
          ('test2', 'gamma'): 2}

How can I return the 'alpha/beta/gamma/delta' of each tuple which has the max value?

i.e.

test1, alpha, 2 #because test1 has 'alpha' as highest value

test2, gamma, 2 #because test2 has 'gamma' as highest value

Would this work?

maxDict={}
for (eachtest,pattern), counter in counts.items():
    maxDict[eachtest,pattern] = max(maxDict.get(eachtest,0),counter)

Thanks.

Upvotes: 0

Views: 789

Answers (2)

Dzinx
Dzinx

Reputation: 57794

You're nearly right. You need to index the dictionary only with test names, and remember both the pattern name and its value as dictionary values. Using max here is a little overkill in my opinion. A simpler code also works and is more readable:

maxDict = {}
for (eachtest, pattern), counter in counts.iteritems():
    _, prev_max = maxDict.get(eachtest, ('', 0))
    if counter > prev_max:
        maxDict[eachtest] = (pattern, counter)

print maxDict
# prints: {'test1': ('alpha', 2), 'test2': ('gamma', 2)}

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601549

First, convert your dict to map the test names to lists of (count, pattern) tuples:

counts2 = collections.defaultdict(list)
for (test, pattern), c in counts.iteritems():
    counts2[test] += (c, pattern)

Now you can get the maxima very easily:

for test, patterns in counts2.iteritems():
    print test, max(patterns)

Upvotes: 2

Related Questions