0

I'm still new to Python while exploring, learning, and today I'm working with JSON and trying to skip every other result. How do I skip, pass, or "continue" every other result? I've tried using continue, iteration, islice, ranges, and next(), but I just cannot quite seem to get this specific behavior done. Here is my code:

import requests, pytemperature, json

r = requests.get('http://samples.openweathermap.org/data/2.5/forecast?
lat=35&lon=139&appid=b1b15e88fa797225412429c1c50c122a1')
dict = r.json()
select_data = dict['list']

for box in select_data:
    if 'dt_txt' in box:
        print(box['dt_txt'], box['main']['temp_min'], box['main']  
 ['temp_max'], box['wind']['speed'], box['weather'][0]['description'])  
    else:
        print('no found')

In above link you can find the complete JSON file, but my output looks like the following(~40 rows total):

2017-11-01 00:00:00 284.786 285.03 1.4 clear sky
2017-11-01 03:00:00 281.496 281.68 1.6 clear sky
2017-11-01 06:00:00 279.633 279.75 1.06 clear sky

Final result should look like

2017-11-01 00:00:00 284.786 285.03 1.4 clear sky
2017-11-01 06:00:00 279.633 279.75 1.06 clear sky

Side note: In the end I am trying to print the date, temp_min, temp_max, main, and description. I will be converting the temp from kelvin to fahrenheit then using gmail to text message me each day the new forecast. Thank you in advance for any help!

SpaceCadet
  • 212
  • 4
  • 14

1 Answers1

2

If select_data is a list, you could slice it.

for box in select_data[::2]:
    if 'dt_txt' in box:
        print(box['dt_txt'], box['main']['temp_min'], box['main']  
 ['temp_max'], box['wind']['speed'], box['weather'][0]['description'])  
    else:
        print('no found')

[::2] is a notation that tells python to retrieve some elements of the list, but, instead of retrieving all of them, it uses steps of two. Here is a great explanation of how this works.

One example for the sake of completeness:

>>> a = [1, 2, 3, 4, 5, 6]
>>> print(a[::2])
[1, 3, 5]
araraonline
  • 1,502
  • 9
  • 14