简体   繁体   中英

How do i make the for loop return the value from a function

So I have tried different methods of returning the data using data from a JSON file running in a loop.

The idea is that I have a config.json file with ip`s that need to be feed to the function when its called upon.

{
    "ip1" : "10.0.0.111",
    "ip2" : "10.0.0.112"
  }
import json
import urllib.request

with open('config.json') as config_file:
    data = json.load(config_file)

def temprature(v):

    urlData = f"http://{v}:8080/getdevice?device=type28_1"
    #print(urlData)
    webURL = urllib.request.urlopen(urlData)
    data = webURL.read()
    encoding = webURL.info().get_content_charset('utf-8')
    tempData = json.loads(data.decode(encoding))
    return tempData["Celsius"]


for (k, v) in data.items():
   #print("Key: " + k)
   temprature(v)
   #print(str(v))

I can`t see or figure out how I can fetch the tempdata and save it to an external variable. I have tried to make a variable that calls the for loop but that failed for me as well.

Edit: Being referred to as a duplicate of This post. But this does not cover the return from a for loop.

You need to save the value to some data structure - list, dictionary, whatever:

temperature_data = []
for (k, v) in data.items():
   #print("Key: " + k)
   temperature_data.append(temprature(v))
   #print(str(v))
    print(temprature(v))

print(temperature_data)

temperature_data = {}
for (k, v) in data.items():
   #print("Key: " + k)
   temperature_data[k] = temprature(v)
   #print(str(v))
   print(temprature(v))

print(temperature_data)

as @ggorlen mentioned, it seems that printing the results is what you'd like to ultimately do, so I added a print statement in the loop.

Make sure to establish the data structure outside of the loop, because otherwise, you'll be writing over the variable on each loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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