如何从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_districtsto 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
districtDataobject) 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
相关产品推荐
相关产品推荐

