I am trying to construct a dictionary with a list of IDs, which will be used as the response from an API. The dict will be used to generate a JSON response.
I am trying to append a list of IDs that have been affected by the request, but am experiencing an error shown below the code.
I have the following code:
data = {"data" : { "message" : "UPDATED TICKETS SUCCESSFULLY", "status" : 200}}
data['data'].append({"child_ids" : child_sr_ids})
The error that I am getting is: AttributeError: 'dict' object has no attribute 'append'
This seems to contradict other sources that I have read such as this: Appending to list in Python dictionary
I am sure I'm doing something simple wrong but I can't work it out. Would appreciate some direction.
edit: title has been changed to better reflect the correct terminology
data["data"] is not a list. It is a dictionary. There isn't a single list in your code. I think what you want to do here is:
data["data"]["child_ids"] = child_sr_ids
You're not appending to a list, you're adding a key to the inner dictionary. What you're looking for is:
data['data']['child_ids'] = child_sr_ids
simply try the line below or use dict update
data["new key"] = "some new entry"
Related
I'm attempting to scrape PGA stats from the API below.
url = 'https://statdata.pgatour.com/r/stats/current/02671.json?userTrackingId=exp=1594257225~acl=*~hmac=464d3dfcda2b2ccb384b77ac7241436f25b7284fb2eb0383184f48cbdff33cc4'
response = requests.get(url)
pga_stats = response.json()
I would like to only select the nested keys identified in this image. I've been able to traverse to the 'year' key with the below code, but I receive the following AttributeError for anything beyond that.
test = pga_stats.get('tours')[0].get('years')
(prints reduced dictionary)
test = pga_stats.get('tours')[0].get('years').get('stats')
'list' object has no attribute 'get'
My end goal is to write this player data to a csv file. Any suggestions would be greatly appreciated.
pga_stats.get('tours')[0].get('years') returns a list, not a dict. You actually want to use the get method on it's first element, like this:
test = pga_stats.get('tours')[0].get('years')[0].get('stats')
I have a rather messy json file one of the pair values of which looks like this.
'response': '{"Results" : [{"results" : [{"id" : "2912362261001","usageLimitType":"allocation","usageLimit":"100","currentUsage":"45","remainingUsage":"55","accountValidThrough":"03-14-2020",\r"GivenName":"John","FamilyName":"Smith", "Email":[{"Address":"mizgier.agata#gmail.com","Label":"personal"}]
I would like to unwrap/tidy it up into the following
'response': "id" : "2912362261001",
"usageLimitType":"allocation",
"usageLimit":"100",
"currentUsage":"45",
"remainingUsage":"55",
"accountValidThrough":"03-14-2020",
"GivenName":"John",
"FamilyName":"Smith",
"Email":"mizgier.agata#gmail.com"}]
Not sure how to get rid of the unnecessary 'results' thing before 'id'
Not sure how to get rid of '\r' before 'Given name' as I don't know what it corresponds to
How do I remove unnecessary 'address' and 'label' from 'Email'?
I am new to json, so any help is appreciated :)
JSON is how you're storing the object, but once you've loaded it into python (using the json loads function) what you get is a dictionary that you can act on just like any other python dict.
object = json.dumps(raw_json)
object = object['Results'][0]
object['email'] = object['email']['address']
The first line converts from json to the object, the second line removes that extra "Results" parent and turns object into the subset you want, and the last line makes email just the address. You don't have to worry about the \r because it wasn't inside of a field and the json dumps removes it.
So I made an API call to JIRA to get the list of all the issues. It returns something like this:
{
issues: [
{
fields: {
description:
summary:
creator:
reporter:
priority:
}
}
]
and I'm trying to get to what's inside fields.
Here's what I have:
response = requests.get(url + '/search?jql=resolution%20=%20Unresolved%20order%20by%20priority%20DESC,updated%20DESC', auth=auth).json()
and then :
response['issues'] works. But I can't find a way to access fields and then the elements inside it. I thought about iterating through but not sure if there's a simpler solution.
My understanding is that response[issues] is a list and I know how to access each element of it response[issues][0] but how to access the object nested inside the list? (still researching on it -- might find an answer)
if you look at your json it's an array to a hash or list to dict. To get fields you'd just call the first array element and the key.
response[issues][0][fields]
I am trying to optimize and reduce some of my code, and just generally understand it better as this is my first development project.
The below works fine but is it possible to simplify it?
self.request.session['path_one_images'] = PATH_ONE_IMAGES
self.request.session['images'] = images
self.request.session['slider_DV_values'] = slider_DV_values
self.request.session['instruction_task_one_images'] = INSTRUCTION_TASK_ONE_IMAGES
self.request.session['instruction_task_two_images'] = INSTRUCTION_TASK_TWO_IMAGES
I tried to combine the separate requests in one using a dict but get the error:
Exception Value: unhashable type: 'list'
self.request.session({['path_one_images'] : PATH_ONE_IMAGES,
['images'] : images,
['slider_DV_values'] : slider_DV_values,
['instruction_task_one_images'] : INSTRUCTION_TASK_ONE_IMAGES,
['instruction_task_two_images'] : INSTRUCTION_TASK_TWO_IMAGES,})
request.session is a basically a Python mapping just like a dictionary, and it supports all dictionary methods. Like dict.update() to set multiple key-value pairs:
self.request.session.update({
'path_one_images': PATH_ONE_IMAGES,
'images': images,
'slider_DV_values': slider_DV_values,
'instruction_task_one_images': INSTRUCTION_TASK_ONE_IMAGES,
'instruction_task_two_images': INSTRUCTION_TASK_TWO_IMAGES
})
Note that the keys are not lists; you were getting confused by the object[...] subscription syntax there.
you know this is wrong syntax for a dict, yes?
{['path_one_images'] : PATH_ONE_IMAGES}
...should be
{'path_one_images': PATH_ONE_IMAGES, etc}
https://docs.python.org/2/library/stdtypes.html#dict
this explains the error you're getting ("unhashable type: 'list'")... Python thinks you're trying to use a list ['path_one_images'] as the dict key. Dict keys don't have to be strings but they have to be hashable. In this case you just want to use the string 'path_one_images'.
Then additionally, as #Martijn Pieters pointed out, the session dict itself isn't callable, you should use the update method, eg:
self.request.session.update({
'path_one_images': PATH_ONE_IMAGES,
'images': images,
'slider_DV_values': slider_DV_values,
'instruction_task_one_images': INSTRUCTION_TASK_ONE_IMAGES,
'instruction_task_two_images': INSTRUCTION_TASK_TWO_IMAGES
})
How can I serialize the entire result set from a search api query on GAE into json? I'm using python and the standard library.
Ive got my results :
index = search.Index(name=Myindex)
query_string = "amount > 0"
results = index.search(query_string)
json_results = {}
I was trying to iterate through them and construct a json output bit by bit,
for i in results:
x = {'result':
{'name' : i.field('name').value,
'value' : i.field('value').value
'geo' : i.field('location').value
}}
json_results = dict(list(json_results)+list(x))
json.dump(json_results,self.response.out)
but I'm totally new to coding and just teaching myself as I go along on this project...Ive tried all manner of variation in the last couple of days, to no avail. There must be a simple way.
You are on the right path, but there are a few errors in your code,
I assume you want to pass back an ordered list of dictionaries holding the results.
At the moment you are constructing a dict of dicts, and the outer dictionary all share the same key "results" which means you will end up with a single entry.
json_results = []
for i in results:
x = {'name' : i.field('name').value,
'value' : i.field('value').value
'geo' : i.field('location').value}
json_results.append(x)
self.response.write(json.dumps(json_results,self.response.out))
In addition you will want to set your content type in the header appropriately. See SO question What is the correct JSON content type? for correct types.