Unable to retun multiple dicitonary sets in python - python

I'm querying a REST API url & I'm trying to return all the dictionary sets, but only able to return one key pair.
Dictionary Output in the print statement inside for loop is the expected output, when when returned only one set of key pair is appearing.
Expected Dictionary looks like:
{'IncidentID': 'IM10265'}
{'IncidentID': 'IM10266'}
{'IncidentID': 'IM10267'}
{'IncidentID': 'IM10268'}
Code:
import json , requests
sm1 = requests.get('http://Rest Url', auth=('XX','YY'))
z = json.loads(sm1.text)
def get_im_list():
incidentlist_access = z['content']
for im_data in incidentlist_access:
Access_imslist = im_data['Incident']
print(Access_imslist)
#print(type(Access_imslist))
#return Access_imslist
data = get_im_list()
#print(data)
So when when I'm un-commentating
return Access_imslist & print(data)
I'm only receiving the output as:
{'IncidentID': 'IM10265'}
not the complete dictionary.

Every time you loop through the data, Access_imslist gets overwritten, so when you (presumably) return Access_Imlist it's only returning the last value.
You need to create a data structure outside of the for loop, add each bit of data to it, then return that instead. Something like:
def get_im_list():
incident_data = []
incidentlist_access = z['content']
for im_data in incidentlist_access:
incident_data.append(im_data['Incident'])
return incident_data
hope that helps!

you need to define a variable list , and then append the Access_imslist values to that variable.
like this :
data = []
def get_im_list():
incidentlist_access = z['content']
for im_data in incidentlist_access:
Access_imslist = im_data['Incident']
data.append(Access_imslist)
print(data)

Related

Append multiple json request as list

I can't seems to wrap my head around this silly issue. There are API requests that run simultaneously 23 different section stored in a dictionary :
polygonsDict = {
'Sect1':'100,6.3',
'Sect2':'100,6.0',
'Sect3':'100,5.5' # and more sections
}
urlDict = {
'traffic': 'https://google.com'
}
Here is the code where I iteratively :
section_key = list(polygonsDict.keys()) #convert the dictionary key to list for iteration
for idx, section in enumerate(section_key):
traffics(section ,urlDict['traffic']+polygonsDict[section]).getPolygonTraffics() #This line is constructing the link for request.
Then, the link is send to a class called traffics with getPolygonTraffics function :
class traffics:
def __init__(self, name, traffics):
self.traffics = traffics
self.name = name
def getPolygonTraffics(self):
try :
print("TRF: Running for "+self.name+"...")
raw = req.get(self.traffics).json()
traffics_raw = [raw] #wrap the dict to list
traffics_ls = []
for ls in traffics_raw:
traffics_ls.append(ls)
#Melt the list of dictionary to form a DataFrame
traffics_df = pd.DataFrame(traffics_ls).explode('jams').reset_index(drop=True)
print(traffics_df)
#exception when `jams` is not found in the list of dict.
except KeyError:
print("Skip!")
In getPolygonTraffics, I want to append every traffics_raw (the json requests) to one individual list and eventually, explode them to a dataFrame. How can I achieve this? I'm not very sure how to explain this.
Current output is multiple lists of each dictionary :
[{}]
[{}]
WHat I want is : [{},{},{}]. Then explode to DataFrame.

store dynamic data in variable python

i my code i have created one function for generate pdf. it can be called more then 2 times in code but at 1st time it can be fetch my data but after second time they give me none value. how can i store my data in list.
i am using list.append but when method call 2nd time then it can be give me null value [that is stored default in database]
my code is:-
def GeneratePdf(request, type):
# data for testing
# global data
template = get_template("employeereport/appointment.html")
# real data
empid = request.GET.get('empid')
Date = request.GET.get('date')
a = []
a.append(Date)
print(a)
output:-
['07/13/2020']
[None]
expected output-
['07/13/2020',None]
declare the list before using it
a = []
def function():
a.append(1)
function()
function()
print(a)

How to return dictionaries from nested loop

I apologize if this is a very basic question, but I built multiple dictionaries using nested loops and I cannot return all the dictionaries, it only returns the first one. I know a part of this is because return is in the wrong indentation, but Python will only allow return data to be indented there. Is there any way to change this function so it returns all the dictionaries?
import urllib.request
import json
def get_url(url):
text = urllib.request.urlopen(url).read().decode()
return text
def display_json(text):
dictionary = json.loads(text)
for item in dictionary['items']:
for article in item['articles']:
line = (article['article'], article['views'])
data = dict([line])
return data
def function(data):
print(data)
def main():
url = "https://wikimedia.org/api/rest_v1/metrics/pageviews/top/en.wikiversity/all-access/2018/01/all-days"
text = get_url(url)
data = display_json(text)
function(data)
main()
Use dictionary comprehension
def display_json(text):
return {
item['article']:item['views'] for item in
json.loads(text)['items'][0]['articles']
}
The JSON is structured as follows:
There is no need to loop through items, b'coz it has only one element. We can just get the first element using json.loads(text)['items'][0]. Even if there is more than one item inside items, you can still manage it inside the comprehension.
use a generator
def display_json(text):
dictionary = json.loads(text)
for item in dictionary['items']:
for article in item['articles']:
line = (article['article'], article['views'])
data = dict([line])
yield data
data = list(display_json(text))

Getting error using gender.py

am trying to tell gender by first name.
I been using this code from:
[https://github.com/block8437/gender.py/blob/master/gender.py][1]
import requests, json
def getGenders(names):
url = ""
cnt = 0
if not isinstance(names,list):
names = [names,]
for name in names:
if url == "":
url = "name[0]=" + name
else:
cnt += 1
url = url + "&name[" + str(cnt) + "]=" + name
req = requests.get("https://api.genderize.io?" + url)
results = json.loads(req.text)
retrn = []
for result in results:
if result["gender"] is not None:
retrn.append((result["gender"], result["probability"], result["count"]))
else:
retrn.append((u'None',u'0.0',0.0))
return retrn
Everything was working for 2 days, I have not change anything in the code. I been passing different names in it on and off for 2 days. Suddenly I got this error:
string indices must be integers
on this line:
if result["gender"] is not None:
First, I want to know why this would suddenly happen? Second, How can I fix it?
Iterating through a dictionary iterates through the keys in a dictionary.
results = {"name":"peter","gender":"male","probability":"0.99","count":796}
[result for result in results] # ['count', 'gender', 'name', 'probability']
Iterating through a list iterates through the items of a list.
results = [{"name":"peter","gender":"male","probability":"0.99","count":796}]
[result for result in results] # [{'count': 796, 'gender': 'male', 'name': 'peter', 'probability': '0.99'}]
According to the API description at https://genderize.io/, there are two response formats: a json object for a single name lookup (which json.loads would return as a dictionary), and a list of objects for multiple lookups (which json.loads would return as a list of dictionaries). See the response for
https://api.genderize.io/?name=peter
compared to
https://api.genderize.io/?name[0]=peter
It seems like your error is the result of getting a response in the first format when you are expecting the second. Why might this have changed? Thats a question for the API you are using. It looks to me like your request should always be in the multi-name request format but I can't speak for how they are actually responding.
As for fixing this, you could check the type and wrap naked dictionaries in a list:
retrn = []
if not isinstance(results, list):
results =[results]
for result in results:
if result["gender"] is not None:
retrn.append((result["gender"], result["probability"], result["count"]))
else:
retrn.append((u'None',u'0.0',0.0))

function using a list in python

I want a function to return me the value of the equation for every number in the list. I have a list of 24 parameters, and I need to solve an equation for every value of this list.
This is the way I get my list:
wlist=[]
def w(i):
for i in range(24):
Calctruesolar=((i*60/1440)*1440+eq_time()+4*long-60*timezone)%1440
if Calctruesolar/4<0:
Calcw=(Calctruesolar/4)+180
wlist.append(Calcw)
print(Calcw)
else:
Calcw=(Calctruesolar/4)-180
wlist.append(Calcw)
print(Calcw)
Then, the list is this one:
>>> wlist=
[166.24797550450222, -178.75202449549778, -163.75202449549778, -148.75202449549778, -133.75202449549778, -118.75202449549778, -103.75202449549778, -88.75202449549778, -73.75202449549778, -58.75202449549778, -43.75202449549778, -28.75202449549778, -13.752024495497778, 1.2479755045022216, 16.24797550450222, 31.24797550450222, 46.24797550450222, 61.24797550450222, 76.24797550450222, 91.24797550450222, 106.24797550450222, 121.24797550450222, 136.24797550450222, 151.24797550450222]
Now, I use the next function:
def hourly_radiation(wlist):
for i in wlist:
Calcrt=(math.pi/24)*(a()+b()*math.cos(math.radians(i)))*((math.cos(math.radians(i)))-math.cos(math.radians(wss())))/(math.sin(math.radians(wss()))-((math.pi*wss()/180)*math.cos(math.radians(wss()))))
CalcI=Calcrt*radiation
print(Calcrt,CalcI)
So, I want to receive Calcrt and CalcI for every value inside the list. But it doesn't work. I have been looking for information in internet and tutorials but I didn't find anything.
Try this:
def hourly_radiation(wlist):
rt_list = []
I_list = []
for i in wlist:
Calcrt = (math.pi/24)*(a()+b()*math.cos(math.radians(i)))*((math.cos(math.radians(i)))-math.cos(math.radians(wss())))/(math.sin(math.radians(wss()))-((math.pi*wss()/180)*math.cos(math.radians(wss()))))
CalcI = Calcrt*radiation
rt_list.append(Calcrt)
i_list.append(CalcI)
print(Calcrt,CalcI)
dict = {}
dict["Calcrt"] = rt_list
dict["CalcI"] = i_list
return dict
This would return the values as a dictionary containing two lists. You may use any data structure that matches your requirements.
You may also create a tuple in each loop run and append it to a list and return it, like:
def hourly_radiation(wlist):
rt_list = []
data = ()
for i in wlist:
Calcrt = (math.pi/24)*(a()+b()*math.cos(math.radians(i)))*((math.cos(math.radians(i)))-math.cos(math.radians(wss())))/(math.sin(math.radians(wss()))-((math.pi*wss()/180)*math.cos(math.radians(wss()))))
CalcI = Calcrt*radiation
data = (Calcrt, CalcI)
print(Calcrt, CalcI)
rt_list.append(data)
return rt_list
I have not run or tested this code, but I hope it should work.
Please use this as a starting point and not as a copy-paste solution.

Categories

Resources