Loop through dictionary with a math function

python

Solution

Don't call it `dict`, that prevents you from accessing the built-in `dict`.

Your keys are `str`ings, so there is no average value. If we convert to `int`s:

dct = dict((tuple(map(int, key)), value) for key, value in str_dict.iteritems())

Which gives:

dct = {(8, 9): 'D', (4, 7): 'C', (6, 1): 'K', (7, 7): 'H', 
       (1, 4): 'A', (3, 8): 'B', (2, 0): 'F', (3, 9): 'G', 
       (4, 2): 'E', (8, 6): 'I', (5, 3): 'J'}

Then you can use `max` on the `sum` of each key:

key = max(d, key=sum)
# (8, 9) is the key with the highest average value

Since the one with the highest `sum` also has the highest average.

If you then want the value for that key, it's:

value = dct[key]
# 'D' is the value for (8, 9)

Problem

I have this dictionary in which in which (key1, key2): value ``` dict = {('1', '4'): 'A', ('3', '8'): 'B', ('4', '7'): 'C', ('8', '9'): 'D', ('4', '2'): 'E', ('2', '0'): 'F', ('3', '9'): 'G', ('7', '7'): 'H', ('8', '6'): 'I', ('5', '3'): 'J', ('6', '1'): 'K'} key1 = input('enter value of key1: ') key2 = input('enter value of key2: ') ``` If I input a pair of key1, key2 and the pair doesn't exist, is there any way that I can loop through this dictionary and pass a math function i.e. to find average value for each pair of keys and print the one that has the biggest average value? Edit: Actually this dictionary was derived from a text file, so it has to be in string first and I need to convert it to int but I don't know how.

Original source