【问题标题】:How to loop inside a json dict and select specific index with Python如何在 json dict 中循环并使用 Python 选择特定索引
【发布时间】:2021-07-13 14:55:04
【问题描述】:

我想为我的项目打印 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},

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

时间 = list_of_data['list'][2]['dt_txt']

data_fore = [time]

for cast in data_fore:
    print(cast)

那么,我如何从这个字典中循环这个值并打印出我需要的值?

我希望我很清楚,感谢您的帮助。

【问题讨论】:

    标签: python json api


    【解决方案1】:

    首先,字典没有排序^。标准 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+ 保留了字典的插入顺序。但是在这种情况下,它来自 API,无法保证顺序。

    【讨论】:

    • 字典是 ordered 从 Python 3.6 开始的。
    • 是的,它们是,但仅当它是在程序中创建时。在这种情况下,字典来自外部 API 调用。
    【解决方案2】:

    假设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
    

    【讨论】:

      【解决方案3】:

      我将字典命名为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
      --------------------------------------------------
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-27
        • 1970-01-01
        • 1970-01-01
        • 2021-02-23
        • 1970-01-01
        • 2018-01-07
        • 1970-01-01
        • 2012-07-31
        相关资源
        最近更新 更多