+ 2
How to Print the Values from a List of Objects?
Let's say I have a list where each element is an object with its own parameters. For example, assuming that each object has three parameters, we have the list:: objects = [objectA, objectB, objectC] When I try to print the list directly I get the addresses of each object, not their values. Is it possible to do something similar to print the values of the objects? Another example of what would be the expected result: "objectA", 20, "Thing", "objectB", 32, "Another Thing", "objectC", 44, "Third Thing" The idea is to make a kind of simple database for studies.
4 Réponses
+ 5
if your objects are class instances you can do this
##### CODE START ####
class Foo():
def __init__(self, x, y):
self.x = x
self.y = y
lst = [Foo(4, 54), Foo(82, 98)]
for o in lst:
print(o.__dict__)
#### CODE END ####
iterate on all instances in the list and print as a dictionary
many many many more options are available
just look up in google and find the one that suits you
+ 10
You could loop your keys.
for key in objects[0]:
print(objects[0][key])
+ 5
glad it worked out :o
+ 2
Wow, thank you both so much. I'm using instances of classes, I did not know this possibility of "converting" it into dictionaries, it seems that I need to review the documentation. Thank you again. o/