简体   繁体   English

使用来自外循环迭代器的值更新特定键的字典值

[英]Update dictionary value for a particular key with value from iterator of outer loop

I have a list of lists in this format:我有一个这种格式的列表:

nrows = ["['Shock pain', 'attack sharp pain']",
         "['bruises', 'lump']",
         "['fever', 'cold', 'Anxiety']",
         "['neck pain', 'headache']"]

I want to call an API by passing everytime 1 list at a time from the nrows list.我想通过从 nrows 列表中每次传递 1 个列表来调用 API。 Each list should be passed 1 by 1 to the data dict with key sList and the response should be saved.每个列表都应以 sList 键一一传递给数据字典,并且应保存响应。

The API function is as follows: API function如下:

newres = []
for i in nrows:
    url = "https://testabcd.io"
    data= {
      "sList": i,
      "kList" : ["age"],
    }
    headers = {
      'Content-Type': 'application/json',
      'Auth': '0644427814339900'
    }
    response = requests.request("GET", url, headers=headers, json=data)
    newres.append(response.text)

    print(response.text)

    print(newres)

Inside the data dict, in sList , at each iteration, I want to pass 1 sublist at a time and get the response appended in a list.sList中的数据字典内部,在每次迭代中,我想一次传递 1 个子列表并将响应附加到列表中。

The current code has all the response same as I think I am unable to iterate and change the value of the data dict with key sList which is what is expected.当前代码的所有响应与我认为我无法迭代并使用键 sList 更改数据字典的值相同,这是预期的。

The csv looks like this: csv 看起来像这样:

['Shock pain', 'attack sharp pain']
['bruises', 'lump']
['fever', 'cold', 'Anxiety']

Assuming the file you work with, really looks like this :假设您使用的文件看起来像这样

['Shock pain', 'attack sharp pain']
['bruises', 'lump']
['fever', 'cold', 'Anxiety']

you can use ast.literal_eval in order to convert the line from the file into list您可以使用ast.literal_eval将文件中的行转换为列表

import requests
from ast import literal_eval

newres = []
url = "https://testabcd.io"
headers = {'Content-Type':'application/json',
           'Auth':'0644427814339900'}

with open("yourfile") as f:
    for line in f:
        data= {"sList": literal_eval(line),
               "kList" : ["age"]}

        response = requests.get(url, headers=headers, json=data)
        newres.append(response.text)
        print(response.text)
        print(newres)

Note:笔记:

  1. This is not tested.这未经测试。
  2. Given that your data comes from non-standard file, where they were exported in bad manner from a dataframe, created unknown how - I would suggest that you seriously reconsider all your workflow and how you manipulate your data.鉴于您的数据来自非标准文件,它们以不良方式从 dataframe 导出,创建方式未知 - 我建议您认真重新考虑所有工作流程以及如何操作数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM