0

I would like to access to attribute of objects in a dictionary in order to find the object with the maximum value on this argument. For example i have this:

class MyClass:
    def __init__(self,name,value):
        self.name=name
        self.value=value


Dict=dict()

object_1 = MyClass("object_1",1)
Dict[object_1.name]=object_1

object_2 = MyClass("object_2",5)
Dict[object_2.name]=object_2

and i would like to do something like:

max(dict.value)

But i can't figure how to acces the attribute of all the object. Can you help me please?

1
  • I already tried it, i got a TypeError because max() doesn't work on instances of "Myclass". I have to find a way to access the attribute of a value of the dictionary. Commented Mar 11, 2020 at 15:21

2 Answers 2

1

Simple genereator fed to max function

max(obj.value for obj in Dict.values())
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you very much !
0

If you want just the max value:

maxval = max(x.value for x in Dict.values())

If you want the key (name) of this object:

name = max(Dict.keys(), key=lambda x: Dict[x.value)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.