Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Get the maximum of a certain index in a dictionary of arrays?

I have a dictionary set up like this:

{attribute: [threshold, infogain]}

where attribute is a string and infogain is a number. The list is always in the same format, so infogain’s index is always 1.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and I would like to find the best attribute based on the value of infogain. I do need to keep threshold in there, or at least I need a way to store this so that all three values are associated and accessible.

My current attempt to get the max value of infogain is this:

max(attribute.values()[1])

Which causes an understandable error saying I’m trying to subscript dict_values.

and I was thinking about how to modify max(attributes, key=attributes.get) to somehow get me the dictionary key for the array with the max infogain, but no luck.

How would I be able to do this?

>Solution :

You can take the max over the key/value pairs of the dictionary:

max_kv = max(d.items(), key = lambda kv:kv[1][1])

Max key is:

max_kv[0]  # since max_kv is a key/value pair

Example:

d = {
    "a1":[0.9, 1],
    "a2":[.25, 2],
    "a3":[.5, 5]
}
max_kv = ('a3', [0.5, 5])

So, max key is:

max_kv[0], which is a3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading