查询dict python http请求

2024-04-27 21:23:13 发布

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

问:编写一个名为“query_dict”的函数,键值存储为将字符串映射到浮点数的参数。该函数将向url“https://fury.cse.buffalo.edu/ps-api/a”发出HTTPS GET请求,其中包含来自输入键值存储区的相同键值对。服务器的响应将是一个JSON字符串,表示格式为“{”answer“}”的对象,其中是一个浮点数。以浮点形式返回键“answer”处的值

import urllib.request
import json
psp = "https://fury.cse.buffalo.edu/ps-api/a"
def query_dict(strfloat):
    query = "?"
    for i in strfloat:
        query += (str(i) + "=" + str(strfloat[i]) + "&")
        query = query [:1]
        response = urllib.request.urlopen(psp + query)
        content_string = response.read().decode()
        content = json.loads(content_string)
        return float(content["answer"])

输入时函数查询不正确[{'z':4,'y':0,'x':5}]

返回值:-1.0 预期:176.7

我怎么解决这个问题?


Tags: 函数字符串answerhttpscontentquerydict键值
1条回答
网友
1楼 · 发布于 2024-04-27 21:23:13

query += (i + "=" + str(strfloat[i]) + "&")

将上述行修改为:

query += (str(i) + "=" + str(strfloat[i]) + "&")注意str()和strfloat[i]后面的括号

Python不能直接添加带有字符串的整数。您必须将整数转换为字符串以进行字符串连接。由于括号的位置不正确,您也没有正确地类型转换strfloat[i]的值。在

编辑:更新后的代码应该如下所示:

def query_dict(strfloat):
    query = "?"

    for i in strfloat:
        query += (str(i) + "=" + str(strfloat[i]) + "&")

    response = urllib.request.urlopen(psp + query)
    content_string = response.read().decode()
    content = json.loads(content_string)
    return float(content["answer"])

相关问题 更多 >