Skip to content Skip to sidebar Skip to footer

How To Convert Lists Of Class Objects To A List Of Their Attributes

guys! So I recently started learning about python classes and objects. For instance, I have a following list of strings: alist = ['Four', 'Three', 'Five', 'One', 'Two'] Which is

Solution 1:

If you are set on using the class, one way would be to use __getattribute__()

print([Numbers().__getattribute__(a) for a in alist])
#[4, 3, 5, 1, 2]

But a much better (and more pythonic IMO) way would be to use a dict:

NumbersDict = dict(
    One=1,
    Two=2,
    Three=3,
    Four=4,
    Five=5
)
print([NumbersDict[a] for a in alist])
#[4, 3, 5, 1, 2]

Solution 2:

Most objects (and hence classes) in python have the __dict__ field, which is a mapping from attribute names to their values. You can access this field using the built-in vars, so

values = [vars(Numbers)[a] for a in alist]

will give you what you want.

Solution 3:

While I totally agree that using a dict for Numbers would be easier and straight forward, but showing you the Enum way as your class involves magic numbers and sort of a valid use case for using enums.

A similar implementation using Enum would be:

from enumimport Enum

classNumbers(Enum): 
    One =1 
    Two = 2 
    Three = 3 
    Four = 4 
    Five = 5

Then you can use getattr and Numbers.<attr>.value to get the constant numbers:

In [592]: alist = ["Four", "Three", "Five", "One", "Two"]                                                                                                                                                   

In [593]: [getattr(Numbers, n).value for n in alist]                                                                                                                                                        
Out[593]: [4, 3, 5, 1, 2]

Edit based on comment:

If you want to get the names back from a number list:

In [952]: l = [4, 3, 5, 1, 2]                                                                                                                                                                               

In [953]: [Numbers(num).name for num in l]                                                                                                                                                                  
Out[953]: ['Four', 'Three', 'Five', 'One', 'Two']

Post a Comment for "How To Convert Lists Of Class Objects To A List Of Their Attributes"