-2

I am trying to print the location of a set of tweets. It is a list with ten dictionaries. I want the location of all ten to be displayed. When I use range it takes just one value. tweets is the list with ten dictionaries. statuses is the key and geo is the object which has the coordinates of the tweet.

for j in range (0,9):
    st1 = tweets[j]['statuses'][j]['geo']
print(j,st1)
ingofreyer
  • 1,086
  • 15
  • 27
S B
  • 1
  • 2
  • 1
    It is unclear what your issue is. Can you share sample of your list of dictionaries? – Ninad Gaikwad Oct 12 '18 at 07:22
  • Not sure if I understood that right, but maybe [enumerate](https://docs.python.org/2.3/whatsnew/section-enumerate.html) could help. – colidyre Oct 12 '18 at 07:22
  • 3
    It seems the print is outside of the for loop (its indentation should match that of the previous line). – Yiftach Oct 12 '18 at 07:23
  • Thanks, the indentation was wrong. – S B Oct 12 '18 at 07:25
  • I am not completely sure what exactly you want to accomplish. Are you asking on how to do a reverse lookup geo-coordinates -> location? Or do you have issues printing the geo coordinates? In that case: you are using `j` twice, which causes you to look for the tenth tweet into the tenth entry in `statuses` which somehow looks like it may not be what you really want (indentation issue aside - I just assume that there may be some whitespace missing in the code example) – ingofreyer Oct 12 '18 at 07:27

3 Answers3

2

If you have a list of 10 dictionaries with the structure you are describing I would do

for i,d in enumerate(tweets):
    print(i, d['statuses']['geo']
Shintlor
  • 742
  • 6
  • 19
1

your print statement is out of for loop. You must write like this:

for j in range (0,9):
    st1 = tweets[j]['statuses'][j]['geo']
    print(j,st1)

UPDATE: I think that, you want to display all tweets and all statuses. In that case you must use nested for loops like:

for j in range(0, 9):
    for i in range(len(tweets[j]['statuses'])):
        st1 = tweets[j]['statuses'][i]['geo']
        print(j, i, st1)

after some optimizations it will look like (if you don't need index):

for tweet in tweets:
    for status in tweet['statuses']:
        st1 = status['geo']
        print(st1)
Axbor Axrorov
  • 2,720
  • 2
  • 17
  • 35
  • I had figured out displaying statuses but was stuck with getting all of them displayed. This helped. Thanks. – S B Oct 12 '18 at 07:41
0

The indentation was wrong.

for j in range (0,10):
   st1 = tweets[j]['statuses'][j]['geo']
   print(j,st1)

This fixed it.

S B
  • 1
  • 2