You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从COVID19India API的JSON中无需指定州名提取所有地区为列表

Extract All Districts from COVID-19 India API into a List

Got it, here's how you can modify your code to pull every district from the API and store them in a single list—no need to hardcode a state name upfront:

import json
import requests

# Fetch the JSON data from the API
url = 'https://api.covid19india.org/state_district_wise.json'
response = requests.get(url)
state_district_data = response.json()

# Initialize an empty list to collect all districts
all_districts = []

# Loop through each state's data
for state_info in state_district_data.values():
    # Grab all district names from the state's districtData
    for district_name in state_info['districtData'].keys():
        all_districts.append(district_name)

# Now you have all districts in the list!
print(all_districts)

Quick breakdown of the code:

  • We use requests.get() to fetch the API data and convert it directly to a Python dictionary with .json()—this replaces the urllib steps for cleaner, more readable code.
  • We create an empty list all_districts to hold our final results.
  • The outer loop iterates through every state's dataset in the JSON response.
  • The inner loop pulls each district name (the keys in the districtData object) and adds it to our list.

If you want to remove duplicate district names (in case different states share the same district name), you can convert the list to a set and back to a list like this:

all_districts_unique = list(set(all_districts))

Note: Using a set will lose the original order of districts. If you need to keep the order while removing duplicates, use collections.OrderedDict instead:

from collections import OrderedDict
all_districts_unique = list(OrderedDict.fromkeys(all_districts))

内容的提问来源于stack exchange,提问作者Sumukh jadhav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:17:30