如何在一个JSON文件中进行for循环以检索多个字典中的数据

2024-10-01 00:21:36 发布

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

我有我制作的天气应用程序。 我有两个问题。 Fist是让我像这样尝试我的代码,它工作得很好,第一部分。但问题是当他们有更多同名城市时。我看不到另一个,因为有了这行代码,我只能找到第一个字典

'''

from tkinter import *
import requests
import json


root = Tk()
root.title("Weather app")
root.geometry("550x400")
root.configure(background="green")
var = IntVar()


def citylookup():

    try:
        api_request = requests.get(
            "http://dataservice.accuweather.com/locations/v1/cities/autocomplete?apikey="
            "xxxxxxxxxxxyyyyyyyyyyxxxxxxxxxxx" + city_search.get() + "&language=fr-FR")

        api = json.loads(api_request.content)
        localisation = api[0]["LocalizedName"]
        region_adm = api[0]["AdministrativeArea"]["ID"]
        id_key = api[0]["Key"]

        # citylabel = Label(root, text=localisation + ", " + region_adm)
        # citylabel.grid(row=1, column=0, columnspan=2)

        button = Button(root, text=localisation + ", " + region_adm, command=forecast)
        button.grid(row=1, column=0)

    except Exception as e:
        api = "Error..."

        def forecast():
            try:
                api_request2 = requests.get("http://dataservice.accuweather.com/forecasts/v1/daily/1day/"
                                        + id_key.get() + "?apikey=xxxxxxxxxxxyyyyyyyyyyxxxxxxxxxxxg&language="
                                                         "fr-FR&details=true&metric=true")

                api2 = json.loads(api_request2.content)

                temperature = api2[0]["Temperature"]["Metric"]["Value"]
                humidite = api2[0]["RelativeHumidity"]
                uvindex = api2[0]["UVIndex"]
                precipitation = api2[0]["PrecipitationSummary"]["Precipitation"]["Metric"]["Value"]
 
                mylabel = Label(root,text="Aujourd'hui il fait \n" + temperature + text + "\nL'humidité relative est de " + humidite + "%\n" + "L'index UV est de " + uvindex + "\nPrécipitation prévue " + precipitation)
                mylabel.grid(row=3, column=0, columnspan=2)

            except Exception as e:
                api = "Error..."


city_search = Entry(root)
city_search.grid(row=0, column=0, stick=W+E+N+S)

city_button = Button(root, text="Ville rechercher", command=citylookup)
city_button.grid(row=0, column=1, stick=W+E+N+S)

root.mainloop()

'''

所以我在json文件中尝试了一个for循环。检索字典中的所有城市名称。(有些城市的名字有一个、其他3个、一些5个或更多。)

对于列表中的i(范围(0,10)): 本地化=api[i][«本地化名称»] 等等

但我只收到一个名字,是字典里的第二个名字。 我不知道这是我的错… 因此,对于第一个问题,我尝试,我要点击按钮“citylookup”,查看字典中所有可用的城市

我遇到的第二个问题是命令=forecast。 如果我让我的代码像这样运行,我会收到一条消息错误(未解析的引用“forecast”)

位如果我将我的函数“def forecast():”放置在没有缩进的位置就可以了预测没有错误,但是我收到了相同的消息error,带有id\u key.get()

如果我把我的函数放在函数citylookup()上:我在citylookup中收到一个(不使用id\u键),在函数“forecast”中收到一个(未解析的引用“id\u键”)

我想做的是点击一个城市,他们给我看天气预报


Tags: textapiidjsoncityget字典column
1条回答
网友
1楼 · 发布于 2024-10-01 00:21:36

我不确定问题中代码的缩进是否与您的代码相同,但我会假设它是相同的

我不明白为什么要在except的范围内定义forecast()函数。我建议首先把这个函数去掉

例如:

def do_get_json(url):
    try:
        response = requests.get(url)
        data = response.content()
        json_data = json.loads(data)
        return json_data
    except Exception as ex:
       raise RuntimeError("Cannot load") from ex

# get city lookup json object
def citylookup(city):
    try:
        # construct the city lookup url here and pass it to do_get_json
        url = "...." + city
        json_data = json_data = do_get_json(url)
        return json_data
    except RuntimeError as ex:
       #handle exception for citylookup
# get forecast json object
def forecast(id_key):
    try:
        # construct the forecast url here and pass it to do_get_json
        url = "..." + id_key
        json_data = do_get_json(url)
        return json_data
    except RuntimeError as ex:
       #handle exception for forecast
.
.
.

这样,这两个函数都可用于整个文件,而不仅仅是单个作用域。 您的错误是由名为范围的内容引起的

在此之后,您可以简单地调用它们,然后解析、循环、保存它

The trick here is that when you define static functions, you must use it after the definition.

python中的非静态函数示例如下:

class SomeClass:
    def __init__(self):
        # body of constructor
    def some_function(self, args):
        # body of function

Notice the self argument. ^^

下面是一个编写TK代码的更好方法的示例:


    root = Tk()
    root.title("Weather app")
    root.geometry("550x400")
    root.configure(background="green")
    var = IntVar()
    
    # use a context dict to keep shared data
    context = {}
    
    city_search = Entry(root)
    city_search.grid(row=0, column=0, stick=W+E+N+S)
    
    def populate_city(context):
        city_obj = citylookup(city_search.get())[0]
        localisation = city_obj["LocalizedName"]
        region_adm = city_obj["AdministrativeArea"]["ID"]
        id_key = city_obj["Key"]
        #save to context
        context.id_key = id_key
    
        citylabel = Label(root, text=localisation + ", " + region_adm)
        citylabel.grid(row=1, column=0, columnspan=2)
    
    city_button = Button(root, text="Ville rechercher", command= lambda: populate_city(context))
    city_button.grid(row=0, column=1, stick=W+E+N+S)
    
    # this probably need more work
    def populate_forecast(context):
        # get key from context
        forcast_obj = forecast(context.id_key)
        for elem in forecast_obj:
            labels = []
            temperature = elem["Temperature"]["Metric"]["Value"]
            humidite = elem["RelativeHumidity"]
            uvindex = elem["UVIndex"]
            precipitation = elem["PrecipitationSummary"]["Precipitation"]["Metric"]["Value"]
     
            mylabel = Label(root,text="Aujourd'hui il fait \n" + temperature + text + "\nL'humidité relative est de " + humidite + "%\n" + "L'index UV est de " + uvindex + "\nPrécipitation prévue " + precipitation)
            mylabel.grid(row=3, column=0, columnspan=2)
            lablels.append(mylable)
    
    button = Button(root, text=localisation + ", " + region_adm, command= lambda: populate_forecast(context))
    button.grid(row=1, column=0)
    
    root.mainloop()

我用粗体字写了这个重要的单词,这样你就可以阅读更多关于这个的内容,而不仅仅是复制/粘贴


要阅读的主题:

  • 上下文和状态
  • 函数编程
  • 重构
  • 异常处理

敬礼

相关问题 更多 >