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?

1
  • 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 Commented May 26, 2013 at 21:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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: 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.
The second loop won't work. The structure is: ` u'user': {u'screen_name': u'NAME' (more stuff) }`
@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. Updated the answer to show that and the contributors (if any).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.