101

How do I iterate over an object's attributes in Python?

I have a class:

class Twitt:
    def __init__(self):
        self.usernames = []
        self.names = []
        self.tweet = []
        self.imageurl = []

    def twitter_lookup(self, coordinents, radius):
        cheese = []
        twitter = Twitter(auth=auth)
        coordinents = coordinents + "," + radius
        print coordinents
        query = twitter.search.tweets(q="", geocode=coordinents, rpp=10)
        for result in query["statuses"]:
            self.usernames.append(result["user"]["screen_name"])
            self.names.append(result['user']["name"])
            self.tweet.append(h.unescape(result["text"]))
            self.imageurl.append(result['user']["profile_image_url_https"])

Now I can get my info by doing this:

k = Twitt()
k.twitter_lookup("51.5033630,-0.1276250", "1mi")
print k.names

I want to be able to do is iterate over the attributes in a for loop like so:

for item in k:
   print item.names
trojek
  • 3,078
  • 2
  • 29
  • 52
Zach Johnson
  • 2,047
  • 6
  • 24
  • 40
  • 1
    what attributes ? you mean over 'k' attributes? – levi Aug 06 '14 at 01:33
  • I may not be using the proper terminology here but yes I want to be able to have my usernames, tweets, etc. returned in some sort of object that i can iterate through them individually. like so: for item in twitter print item.usernames. Something along those lines. – Zach Johnson Aug 06 '14 at 01:41
  • try my answer and see if works for you. – levi Aug 06 '14 at 01:43

3 Answers3

153

UPDATED

For python 3, you should use items() instead of iteritems()

PYTHON 2

for attr, value in k.__dict__.iteritems():
        print attr, value

PYTHON 3

for attr, value in k.__dict__.items():
        print(attr, value)

This will print

'names', [a list with names]
'tweet', [a list with tweet]
Joshua Schlichting
  • 3,110
  • 6
  • 28
  • 54
levi
  • 22,001
  • 7
  • 73
  • 74
  • 7
    k.iteritems() was removed in Python3, use k.items() instead. – trdavidson Sep 18 '16 at 22:11
  • 1
    @trdavidson I added the note. – levi Sep 18 '16 at 22:13
  • 3
    Also new in python3 you need parens for the print operation. – Free Url Oct 08 '17 at 00:58
  • Hidden `__dict__` method very useful! Also, to return as a dict use a dict comprehension `print({attr:value for attr, value in k.__dict__.iteritems()})` – Davos Mar 13 '18 at 02:40
  • 1
    I tried this on an object which is inheriting from another one, and it only returned the properties belonging to the base class. – alex Jun 08 '18 at 19:21
  • 1
    This works if and only if the object has a `__dict__` attribute. This is [not always true](https://docs.python.org/3/reference/datamodel.html#slots), and you should iterate through `__slots__` if it doesn't. – Konstantin Sekeresh Nov 29 '19 at 11:47
43

You can use the standard Python idiom, vars():

for attr, value in vars(k).items():
    print(attr, '=', value)
arekolek
  • 9,128
  • 3
  • 58
  • 79
9

Iterate over an objects attributes in python:

class C:
    a = 5
    b = [1,2,3]
    def foobar():
        b = "hi"    

for attr, value in C.__dict__.iteritems():
    print "Attribute: " + str(attr or "")
    print "Value: " + str(value or "")

Prints:

python test.py
Attribute: a
Value: 5
Attribute: foobar
Value: <function foobar at 0x7fe74f8bfc08>
Attribute: __module__
Value: __main__
Attribute: b
Value: [1, 2, 3]
Attribute: __doc__
Value:
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335