bouaaah
bouaaah

Reputation: 35

Python - Access to all attributes in a dictionnary

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?

Upvotes: 0

Views: 50

Answers (2)

mad_
mad_

Reputation: 8273

Simple genereator fed to max function

max(obj.value for obj in Dict.values())

Upvotes: 1

Błotosmętek
Błotosmętek

Reputation: 12927

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)

Upvotes: 0

Related Questions