3

I'm a newbie to Python and JSON as well. I installed twython to "speak" to the Twitter API. I use Python 2.7 on a mac.

I would like to get my mentions through the API. The program should identify the Twitter user who mentioned me.

I try:

t = Twython(...)
men = t.get_mentions_timeline()

The user is mentioned once, print men shows a lot of stuff like this:

[{u'contributors': None, u'truncated': False, u'text': .... u'Sun May 26 09:18:55 +0000 2013', u'in_reply_to_status_id_str': None, u'place': None}]

Somewhere in this stuff I see all the things I would like to extract from the response.

How can I extract the screen_name?

I'm quite confused with json.dumps or json.loads - shall I work with json or simplejson?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
hildwin
  • 95
  • 1
  • 1
  • 5
  • I've got the solution - only one for: for mention in men: mu = mention ['user'] tweetid = mention ['id'] usern = mu['screen_name'] print tweetid print usern – hildwin May 26 '13 at 21:17

1 Answers1

2

You don't need to use json (or simplejson, which is the exact same library; it was renamed when bundled with Python); the Twython library already decoded everything from JSON for you.

You got a list from the API, each entry is a dict; each such dictionary is a Tweet. You can see what is contained in the Twitter API documentation. Loop over that list; some items are dictionaries or lists themselves:

for mention in men:
    print mention['user']['screen_name']
    if mention['contributors']:
        print [con['screen_name'] for con in mention['contributors']]

To figure out the full structure, use pprint.pprint() to print a structured version:

import pprint

pprint.pprint(men)

which will make it easier for you to figure out what you can loop over, etc.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks, but I get an error: KeyError: 'screen_name' perhaps I should mention that screen_name is part of the entities Looks like this: u'entities': {u'symbols': [], u'user_mentions': [{u'id': 1457484992, u'indices': [0, 8], u'id_str': u'1457484992', u'screen_name': u'CyclopT', .... – hildwin May 26 '13 at 17:25
  • @hildwin: I had an error in an earlier edit; can you tell me what you used? Use the `pprint` trick to figure out what is a list and what is a dictionary. – Martijn Pieters May 26 '13 at 17:28
  • The second loop won't work. The structure is: ` u'user': {u'screen_name': u'NAME' (more stuff) }` – hildwin May 26 '13 at 18:12
  • @hildwin: Right, I was homing in on the `contributors` key (which was `None` in your first example, so that wouldn't work). The `user` key *also* has a `screen_name` key. The API link I pointed to includes a link for the `user` key, pointing to the [Users page](https://dev.twitter.com/docs/platform-objects/users). Updated the answer to show that *and* the contributors (if any). – Martijn Pieters May 26 '13 at 20:26