Reputation: 7490
I have a dictionary with objects being stored as values. How might I access and print the attributes of a particular object? For example,
dict={0:obj0, 1:obj1, 2:obj2, 3:obj3}
I want to print obj1.attribute. I have tried:
print (dict[key]).attribute
to no avail. I cannot just access the object directly because I have not assigned it to a variable. This program automatically generates objects and places them in dict with an automatically generated key, which spares me manual assignment of an arbitrary amount of values. If anyone knows a better way to phrase this question, please go ahead. Thank you so much!
EDIT: My dictionary's name is not 'dict', nor is my attribute named 'attribute.' These are used simply for clarity.
EDIT: OK, here's what's going on. I'm using Tkinter to retrieve contact information through entry fields. I'm using that input to create an object with attributes name, address, etc. So,
class User():
def __init__(self, name='', street='', city='', state='', zip=''):
self.name=name
self.street=street
self.city=city
self.state=state
self.zip=zip
###### code below is outside of class User #####
def make(name='', street='', city='', state='', zip='', count=0):
dic[count]=User(name='', street='', city='', state='', zip='')
Is there a reason that "dic[0].name" would return an empty string?
Upvotes: 2
Views: 9867
Reputation: 13600
Change this
def make(name='', street='', city='', state='', zip='', count=0):
dic[count]=User(name='', street='', city='', state='', zip='')
to
def make(name='', street='', city='', state='', zip='', count=0):
dic[count]=User(name=name, street=street, city=city, state=state, zip=zip)
In case your attribute is containing whitespaces or an empty string, you can do that in some case, it will help you know if something is there.
print "<%s>" % my_dict[key].attribute
If you see <>
it's likely that this is an empty string, if you see something else in between, it could be spaces are tabs or newlines or anything that isn't visible.
The other possibility is that for some reasons, the attribute
you're getting is an object that override __repr__
or __str__
and returns an empty string. Without knowing with what you're dealing with, it is very hard to help more than that.
Upvotes: 1