如何在json dict中循环并使用Python选择特定索引

2024-09-30 10:32:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为我的项目打印5天的天气预报。当我提出请求时,我会得到一个巨大的JSON字典,它带有相同的参数,重复了五天,不同的时间

这是格言的一部分

    {'city': {'coord': {'lat': 43.55, 'lon': 13.1667},
          'country': 'IT',
          'id': 3183087,
          'name': 'Provincia di Ancona',
          'population': 478319,
          'sunrise': 1626147487,
          'sunset': 1626202058,
          'timezone': 7200},
 'cnt': 40,
 'cod': '200',
 'list': [{'clouds': {'all': 97},
           'dt': 1626188400,
           'dt_txt': '2021-07-13 15:00:00',
           'main': {'feels_like': 31.67,
                    'grnd_level': 990,
                    'humidity': 47,
                    'pressure': 1006,
                    'sea_level': 1006,
                    'temp': 30.75,
                    'temp_kf': -4.44,
                    'temp_max': 35.19,
                    'temp_min': 30.75},
           'pop': 0,
           'sys': {'pod': 'd'},
           'visibility': 10000,
           'weather': [{'description': 'overcast clouds',
                        'icon': '04d',
                        'id': 804,
                        'main': 'Clouds'}],
           'wind': {'deg': 211, 'gust': 12.79, 'speed': 9.41}},
          {'clouds': {'all': 97},
           'dt': 1626199200,
           'dt_txt': '2021-07-13 18:00:00',
           'main': {'feels_like': 30.93,
                    'grnd_level': 990,
                    'humidity': 50,
                    'pressure': 1006,
                    'sea_level': 1006,
                    'temp': 29.92,
                    'temp_kf': 1.67,
                    'temp_max': 29.92,
                    'temp_min': 28.25},
           'pop': 0.12,
           'sys': {'pod': 'd'},
           'visibility': 10000,
           'weather': [{'description': 'overcast clouds',
                        'icon': '04d',
                        'id': 804,
                        'main': 'Clouds'}],
           'wind': {'deg': 246, 'gust': 10.79, 'speed': 6.88}},
          {'clouds': {'all': 81},
           'dt': 1626210000,
           'dt_txt': '2021-07-13 21:00:00',
           'main': {'feels_like': 27.85,
                    'grnd_level': 991,
                    'humidity': 57,
                    'pressure': 1007,
                    'sea_level': 1007,
                    'temp': 26.98,
                    'temp_kf': 1.89,
                    'temp_max': 26.98,
                    'temp_min': 25.09},
           'pop': 0.26,
           'sys': {'pod': 'n'},
           'visibility': 10000,
           'weather': [{'description': 'broken clouds',
                        'icon': '04n',
                        'id': 803,
                        'main': 'Clouds'}],
           'wind': {'deg': 237, 'gust': 14.36, 'speed': 7.51}},
          {'clouds': {'all': 37},
           'dt': 1626220800,
           'dt_txt': '2021-07-14 00:00:00',
           'main': {'feels_like': 19.41,
                    'grnd_level': 993,
                    'humidity': 61,
                    'pressure': 1009,
                    'sea_level': 1009,
                    'temp': 19.78,
                    'temp_kf': 0,
                    'temp_max': 19.78,
                    'temp_min': 19.78},
           'pop': 0.26,
           'sys': {'pod': 'n'},
           'visibility': 10000,
           'weather': [{'description': 'scattered clouds',
                        'icon': '03n',
                        'id': 802,
                        'main': 'Clouds'}],
           'wind': {'deg': 273, 'gust': 6.66, 'speed': 4.17}},
          {'clouds': {'all': 0},
           'dt': 1626231600,
           'dt_txt': '2021-07-14 03:00:00',
           'main': {'feels_like': 16.32,
                    'grnd_level': 993,
                    'humidity': 64,
                    'pressure': 1010,
                    'sea_level': 1010,
                    'temp': 16.9,
                    'temp_kf': 0,
                    'temp_max': 16.9,
                    'temp_min': 16.9},

我要打印的值是name、city、wind、dt_txt。前两个值始终相同,但其他两个具有不同的索引值。 我写了这个简单的循环来开始如何做,但我意识到索引值在dict中的变化(不总是相同的计数,我也尝试在特定的索引上重复循环,但没有成功),我不知道如何解决这个问题。当然,我可以手动保存变量中的所有“时间”和“风”值,但这是一项巨大的工作

时间=数据列表['list'][2]['dt_txt']

data_fore = [time]

for cast in data_fore:
    print(cast)

那么,我如何从这个dict循环这个值并打印出我需要的值呢

我希望我说的很清楚,谢谢你的帮助


Tags: txtidmaindtallleveltemplike
3条回答

首先也是最重要的一点是,字典不是有序的。在标准Python字典中没有什么比索引更好的了

要实现您想要的功能,下面的代码应该执行以下操作(我假设,键总是相同的):

for each in result["list"]:
    print("_" * 50)
    print("wind", each["wind"])
    print("city", result["city"])
    print("name", result["city"]["name"])
    print("dt_txt", each["dt_txt"])

对问题中的数据运行上述代码会导致:

__________________________________________________
wind {'deg': 211, 'gust': 12.79, 'speed': 9.41}
city {'coord': {'lat': 43.55, 'lon': 13.1667}, 'country': 'IT', 'id': 3183087, 'name': 'Provincia di Ancona', 'population': 478319, 'sunrise': 1626147487, 'sunset': 1626202058, 'timezone': 7200}
name Provincia di Ancona
dt_txt 2021-07-13 15:00:00
__________________________________________________
wind {'deg': 246, 'gust': 10.79, 'speed': 6.88}
city {'coord': {'lat': 43.55, 'lon': 13.1667}, 'country': 'IT', 'id': 3183087, 'name': 'Provincia di Ancona', 'population': 478319, 'sunrise': 1626147487, 'sunset': 1626202058, 'timezone': 7200}
name Provincia di Ancona
dt_txt 2021-07-13 18:00:00

^Python 3.6+ preserves the insertion order of a dictionary. However in this case, it's coming from an API, order is not guaranteed.

我把字典命名为json

print('Name:',json['city']['name'])
print('City:',json['city'])
print('#'*50)

for item in json['list']:
    print('Wind:', item['wind'])
    print('dt_txt:', item['dt_txt'])
    print('-'*50)

输出:

Name: Provincia di Ancona
City: {'coord': {'lat': 43.55, 'lon': 13.1667}, 'country': 'IT', 'id': 3183087, 'name': 'Provincia di Ancona', 'population': 478319, 'sunrise': 1626147487, 'sunset': 1626202058, 'timezone': 7200}
##################################################
Wind: {'deg': 211, 'gust': 12.79, 'speed': 9.41}
dt_txt: 2021-07-13 15:00:00
                         
Wind: {'deg': 246, 'gust': 10.79, 'speed': 6.88}
dt_txt: 2021-07-13 18:00:00
                         
Wind: {'deg': 237, 'gust': 14.36, 'speed': 7.51}
dt_txt: 2021-07-13 21:00:00
                         
Wind: {'deg': 273, 'gust': 6.66, 'speed': 4.17}
dt_txt: 2021-07-14 00:00:00
                         

假设d是您的字典,这段代码将打印您需要的数据

您可以在d['list']上迭代并提取数据,因为它们也是dictionary

print(f"Name: {d['city']['name']}")
print(f"City: {d['city']}")
for i in d['list']:
    print(f"Wind: {i.get('wind')}")
    print(f"Time: {i.get('dt_txt')}")
    print('\n')
Sample Output:

Name: Provincia di Ancona
City: {'coord': {'lat': 43.55, 'lon': 13.1667}, 'country': 'IT', 'id': 3183087, 'name': 'Provincia di Ancona', 'population': 478319, 'sunrise': 1626147487, 'sunset': 1626202058, 'timezone': 7200}


Wind: {'deg': 211, 'gust': 12.79, 'speed': 9.41}
Time: 2021-07-13 15:00:00


Wind: {'deg': 246, 'gust': 10.79, 'speed': 6.88}
Time: 2021-07-13 18:00:00


Wind: {'deg': 237, 'gust': 14.36, 'speed': 7.51}
Time: 2021-07-13 21:00:00


Wind: {'deg': 273, 'gust': 6.66, 'speed': 4.17}
Time: 2021-07-14 00:00:00

相关问题 更多 >

    热门问题