skip to Main Content

I am learning to use Python and Twitter API. The information of a user was saved as json file.

Basically the json file stored a list of dictionaries:

data = [{1}, {2}, {3}, {4}, {5}]

In each dictionary there are some information, f.ex.:

[
  {
    "created_at": "2018-04-28 13:12:07", 
    "favorite_count": 0, 
    "followers_count": 2, 
    "id_str": "990217093206310912", 
    "in_reply_to_screen_name": null, 
    "retweet_count": 0, 
    "screen_name": "SyerahMizi", 
    "text": "u can count on me like 123 ud83dude0aud83dudc6d"
  }, 
  {
    "created_at": "2018-04-26 04:21:48", 
    "favorite_count": 0, 
    "followers_count": 2, 
    "id_str": "989358860937846785", 
    "in_reply_to_screen_name": null, 
    "retweet_count": 0, 
    "screen_name": "SyerahMizi", 
    "text": "Never give up"
  }, 
]

I am simply trying to print only the “text” information in each dictionary but I kept getting an error

TypeError: list indices must be integers, not str

Here is what I have so far:

import json
    with open('981452637_tweetlist.json') as json_file:
        json_data = json.load(json_file)
        lst = json_file['text'][0]
        print lst

so any help or explanation as to what I need would be great. Thank you!

2

Answers


  1. As error is suggesting, list indices must be ‘int’ not ‘str’. You are mistakenly taking list as dictionary and dictionary as list. Correct code will be:

    import json
        with open('981452637_tweetlist.json') as json_file:
            json_data = json.load(json_file)
            lst = json_file[0]['text']              #change here
            print lst
    
    Login or Signup to reply.
  2. You can use a for-loop.

    for d in json_data:
        print(d["text"])
    

    If you wanted it on the same line, you can instead make a list and append to it in the for-loop.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search