List Attributes of an Object

Get all object attributes in Python?

Use the built-in function dir().

How to list the properties of a JavaScript object?

In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in Object.keys method:

var keys = Object.keys(myObject);

The above has a full polyfill but a simplified version is:

var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}

Alternatively replace var getKeys with Object.prototype.keys to allow you to call .keys() on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.

How can i print the attributes of an object list that stores objects?

Implement __str__ or __repr__ for Dog so Python knows how to represent it.

class Dog:
def __init__(self, name, age):
self.__name = name
self.__age = age
def __repr__(self):
return f"Dog({self.__name}, {self.__age})"
def __str__(self):
return f"Woof! I'm {self.__name}, and I'm {self.__age} years old!"

More information about __str__ and __repr__ can be found here

Extract list of attributes from list of objects in python

You can also write:

attr=(o.attr for o in objsm)

This way you get a generator that conserves memory. For more benefits look at Generator Expressions.

How to create a list with an attribute taken from objects of a list in kotlin

You can simply map one list to another.

val ageList = persons.map { it.age }

You could also replace the explicit lambda with a function reference.

val ageList = persons.map(Person::age)

If you need to have an ArrayList<Int> as result, you can use the mapTo function to map into an ArrayList<Int> instead of the default List<Int>.

val ageList = persons.mapTo(arrayListOf()) { it.age }

This assumes you have a dataset along the lines of:

data class Person(val name: String, val age: Int)

val persons = listOf(
Person("Pete", 31),
Person("Luna", 19),
Person("Hendrick", 45),
)

Python - creating a reference tree of objects by their attributes

If you have to deal with upwards of one million objects, generating an additional hierarchy is probably not the best solution. It would require many additional objects and waste a lot of time for just creating the hierarchy. The hierarchy would also need to be updated whenever list_of_objects change.

Therefore, I suggest a more generic and dynamic approach by using iterators and a XPath like principle. Let's call it OPath. The OPath class is a lightweight object, which simply concatenates the attributes to a kind of attribute path. It also keeps a reference to the original list of entry objects. And finally, it is based on attributes only and so works for any type of object.

The actual lookup happens, when we start iterating through the OPath object (e.g., putting the object into a list(), using a for-loop, ...). The OPath returns an iterator, which recursively looks up the matching objects according to the attribute path based on the actual content in the originally supplied list. It yields one matching object after another to avoid the creation of unnecessary lists with entirely populated matching objects.

class OPath:
def __init__(self, objects, path = []):
self.__objects = objects
self.__path = path

def __getattr__(self, __name):
return OPath(self.__objects, self.__path + [__name])

def __iter__(self):
yield from (__object for __object in self.__objects if self.__matches(__object, self.__path))

@staticmethod
def __matches(__object, path):
if path:
if hasattr(__object, path[0]):
return OPath.__matches(getattr(__object, path[0]), path[1:])
if __object == path[0] and len(path) <= 1:
return True
return False
return True

if __name__ == '__main__':
class State:
def __init__(self, state_dictionary):
self._state_dictionary = state_dictionary
for key, value in self._state_dictionary.items():
if isinstance(value, dict):
value = State(value)
setattr(self, key, value)

o1 = State({ "country":"Kenya", "disease": "breast cancer" })
o2 = State({ "country":"Kenya", "disease": "diabetes" })
o3 = State({ "country":"Ireland", "risk_factor": { "smoking":"Current" } })
o4 = State({ "country":"Kenya", "risk_factor": { "smoking":"Previous" } })

# test cases with absolute paths
print("Select absolute")
path = OPath([o1, o2, o3, o4])
print(list(path) == [o1, o2, o3, o4])
print(list(path.country) == [o1, o2, o3, o4])
print(list(path.country.Kenya) == [o1, o2, o4])
print(list(path.disease) == [o1, o2])
print(list(path.disease.diabetes) == [o2])
print(list(path.risk_factor.smoking) == [o3, o4])
print(list(path.risk_factor.smoking.Current) == [o3])
print(list(path.doesnotexist.smoking.Current) == [])
print(list(path.risk_factor.doesnotexist.Current) == [])
print(list(path.risk_factor.smoking.invalidvalue) == [])
print(list(path.risk_factor.doesnotexist.Current.invalidpath) == [])

# test cases with relative paths
country = OPath([o1, o2, o3, o4], ["country"])
print("Select relative from country:")
print(list(country) == [o1, o2, o3, o4])
print(list(country.Kenya) == [o1, o2, o4])

print("Select all with country=Kenya")
kenya = OPath([o1, o2, o3, o4], ['country', 'Kenya'])
print(list(kenya) == [o1, o2, o4])

Output is expected to be True for all test cases.

Extract a list of specific attributes from a list of objects

If you want a list of dictionaries of object attributes:

# the list of attributes to get from each object
attrs = ['attr1', 'attr2']

# using dictionary comprehension to generate the list of attributes and their values
attr_vals_dict = [{a:getattr(o, a) for a in attrs} for o in objects]

Output:

[{'attr1': 1, 'attr2': 2}, {'attr1': 3, 'attr2': 4}, {'attr1': 'banana', 'attr2': 'apple'}]

As far as getting the dynamic list of attributes in the first place, that's already been answered here.



Related Topics



Leave a reply



Submit