Gthoma2
Gthoma2

Reputation: 707

Possible to use string to refer to object property?

I couldn't find a related question in StackOverflow, so...

I have a dictionary filled with data on planets and stars in the form of:

dict = {'name': value, 'mass' : value, 'radius': value, etc..}

the keys of this dictionary have the same name of the properties of the Planet and Star class that I am assigning their value to.

What I would like to do is to count the amount of missing information for all of the populated Star and Planet objects after I calculate certain missing fields of data based on other populated fields...

Is there any way to step through the keys of this dictionary and reference the property of Star/ Planet objects with the string that the key holds?

So something like:

for planetObjs in planets:
    for key in dict.iterkeys():
        if planetObj.key == None:
            countMissingDict[key] += 1  

How would I refer to the string that key holds which is the same string used as the attribute within a Planet object? Is this possible?

Upvotes: 2

Views: 356

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251001

Use getattr:

getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case

You can shorten your code to:

from collections import Counter
countMissingDict = Counter(key for planetObjs in planets for key in dic
                                         if getattr(planetObjs, key) is None)

Note: Don't use dict as a variable name.

Upvotes: 4

Christian Ternus
Christian Ternus

Reputation: 8492

You want to use getattr.

for planetObj in planets:
    for key in dict.iterkeys():
        if getattr(planetObj, key) == None:
            countMissingDict[key] += 1  

Upvotes: 0

Related Questions