-4

Currently my data set is:

{('NSW', '06'): 0.4, ('QLD', '06'): 0.2, ('VIC', '06'): 0.0, ('NSW', '07'): 0.2, ('QLD', '07'): 0.4, ('VIC', '07'): 0.0, ('NSW', '08'): 0.2, ('QLD', '08'): 0.2, ('VIC', '08'): 0.0, ('NSW', '09'): 0.2, ('QLD', '09'): 0.2, ('VIC', '09'): 0.0, ('NSW', '10'): 0.2, ('QLD', '10'): 0.2, ('VIC', '10'): 0.0, ('NSW', '11'): 0.2, ('QLD', '11'): 0.6, ('VIC', '11'): 0.0}

I have achieved this from doing:

key = (state,month)
    if key not in rainfall_and_month:
        rainfall_and_month[key] = rainfall
    if key in rainfall_and_month:
        rainfall_and_month[key] = min(rainfall, rainfall_and_month[key])

I wish to print out the largest value out of the key-value pairs. So basically I would like to make the code find "('QLD', '11'): 0.6", and then print out,

A-value: QLD
B-value: 11

separately, so I would probably end up doing

print("A-value:", state)
print("B-value:", month)

However I'm not sure as to how to find the largest value then extract those data points.

P. Parker
  • 1
  • 2

3 Answers3

0

In Python 3, dictionaries have a method called .items() which returns a generator of the dictionary items as a tuple of tuples. Python 2 equivalent is .iteritems(). In your case, if the dict is named data_dict

dict_items = data_dict.items()

The max function in Python allows you to enter a lambda function, which basically tells it what value to compare by.

max_item_tuple = max(dict_items, key=lambda currentTuple: currentTuple[1])

Now your max_item_tuple contains the tuple of the key value pair that you need from your dict.

For example, if I had a dictionary of {"something": 1, "nothing": 4, "everything": 3}, my max_item_tuple would become ("nothing", 4).

rassa45
  • 3,482
  • 1
  • 29
  • 43
0

here is an alternative to lambda:

>>> max_pair = max(data.items(), key=operator.itemgetter(1))
('QLD', '11')
>>> max_pair[0]
'QLD'
>>> max_pair[1]
'11'
Ali Yılmaz
  • 1,657
  • 1
  • 11
  • 28
0

Use max to find max of value. It takes a keyword parameter key which can be assigned to value based on what you need to find the maximum of.

Consider using operator module. operator.itemgetter(1) takes the value of each key in every iterations.

import operator

s = {('NSW', '06'): 0.4, ('QLD', '06'): 0.2, ('VIC', '06'): 0.0, ('NSW', '07'): 0.2, ('QLD', '07'): 0.4, ('VIC', '07'): 0.0, ('NSW', '08'): 0.2, ('QLD', '08'): 0.2, ('VIC', '08'): 0.0, ('NSW', '09'): 0.2, ('QLD', '09'): 0.2, ('VIC', '09'): 0.0, ('NSW', '10'): 0.2, ('QLD', '10'): 0.2, ('VIC', '10'): 0.0, ('NSW', '11'): 0.2, ('QLD', '11'): 0.6, ('VIC', '11'): 0.0}

result = max(s.items(), key=operator.itemgetter(1))

A_value = result[0][0]  # QLD
B_value = result[0][1]  # 11
Austin
  • 25,759
  • 4
  • 25
  • 48