keyerror while checking for values that exists in a dictionary - python

I keep getting a keyerror in python.
I am using requests and getting back a json with 3 values. I am trying to extract only the elevation.
r = requests.get(api_url +str(lat) +"," +str(longi) )
resp = json.loads(r.text)
print(resp)
print(resp['elevation'])
this is the response for resp:
{'results': [{'latitude': 30.654543, 'longitude': 35.235351, 'elevation': -80}]}
this is the error:
KeyError: 'elevation'

If you format the JSON (resp) a bit to be easier to undestand, you get something like this:
{
"results":[
{
"latitude":30.654543,
"longitude":35.235351,
"elevation":-80
}
]
}
(I used this tool)
You can see that the "toplevel" is an object (loaded as a python dict) with a single key: "results", containing an array of objects (loaded as a python list of dicts).
resp['results'] would be [{'latitude': 30.654543, 'longitude': 35.235351, 'elevation': -80}] - the said array
resp['results'][0] would be the 1st element of that array: {'latitude': 30.654543, 'longitude': 35.235351, 'elevation': -80}
resp['results'][0]['elevation'] would be -80
I suggest using a for loop to iterate trough the elements of resp['results'] to process all resoults.

It is responding with a list (holding one dictionary) as the value. So you would access with resp["results"][0]["elevation"] because "elevation" is not in results, it is in results[0] (zero index of the list results) and you can tell this by the "[{ }]" denoting a list holding a dictionary.

The response is a dictionary whose 'results' key holds a list of dictionaries. In your case this list holds only one entry. So, you must traverse the entire path to get the value you want.
Try:
resp['results'][0]['elevation']

Related

How to extract a key pair value from a JSON array?

I'm using a GET query string to locate a specific record. The correct result is returned in JSON, but in an array of one (it allows for multiple items, but as I'm using a unique key in my query string, there will only ever be one item returned, but's it's still in an array). I've been able to extract the value of a specific key pair from a JSON result before, but this time the fact that this particular result is in an array has got me stumped. I'm a set of square brackets away from success :-(
Here's the JSON response, and I want the value of 'Id':
{
'#odata.context': 'https://foo.bar.com/mySite/api/v2/object/$metadata#MuseuSensorData_SensorDeviceObject',
'value':
[
{
'Id': '02cb9c0f-89ca-46fd-882e-5d770d7da214',
'DateCreated': '2022-07-13T14:05:22.24+01:00',
'DeviceName': 'Cabinet 2 Sensor 1',
'IsActive': True,
'SerialNumber': '1234'
}
]}
In amongst my Python code, extract below, I'm trying to return the value of 'Id', but all I get is any one of a number of errors (latest is TypeError: string indices must be integers), which I know relates to indices/dictionaries and something called slices, and navigating through to the desired section, but I'm new to Python (as of this week), and it's got me spinning.
response = requests.request("GET", url, headers=headers)
data = response.text
print(data[0]['value']['Id'])
Looks like I was almost there. Thanks to Kacper, I now have my code in the right order:
data = response.text
parsed_json = json.loads(data)
RecID = parsed_json['value'][0]['Id']
print(RecID)

TypeError when trying to iterate and compare values in a list and dict

I am trying to iterate over a list that is an import of a json and a dict where I want to store the values of the list in the value place. The problem is that when I loop over the list and do a comparative if statement I get this error message
if i["service"] == serviceIp[i]:
TypeError: unhashable type: 'dict'
The dict where I would like to store the addresses for the services
serviceIp = {
"service-A": "",
"service-B": ""
}
The list import from json which includes all the addresses
serviceAddress
[{'service': 'service-A', 'address': ['localhost1']}, {'service': 'service-B', 'address': ['localhost2']}]
This is my loop and if statement
for i in serviceAddress:
if i["service"] == serviceIp[i]:
Any idea what is causing this error? My goal is to compare the keys for service and store the service values into the values of the dict
i value in the for loop is a dict. ex: {'service': 'service-A', 'address': ['localhost1']} and can't be used as keys for dict.
If you want to store addresses for service names in dict you can do this:
for s in serviceAddress:
serviceIp[s["service"]] = s["address"]
Or if you wan't to make sure to only add services that their names are already in the serviceIp dict:
for s in serviceAddress:
if s["service"] in serviceIp:
serviceIp[s["service"]] = s["address"]

Get the values from a list of dictionaries which have dictionaries nested in them using python

I am loading objects from json file and putting it in a list. I want to access the value of "details". I have tried something like this -
item_list = [{
"text": "some text here",
"timestamp": "Tue Jun 30 16:46:48 +0000 2020",
"details": "{'id': '1278007086765522944', 'hash': ['e66d35b329a7c2cff66075eaf4530d13']}"}]
for d in item_list.iterkeys():
print(d['item'])
but I am getting UndefinedError: 'unicode object' has no attribute 'iterkeys'
Be careful that item_list is a list not a dictionary and iterkeys() only works on dictionaries.
Anyway, one solution is to perform the following steps:
take each element in item_list (the elements would be dictionaries)
get the list of values of each dictionary from above
check the type of the value and if it is a dictionary itself, then extract the values of that dictionary and process them in any way you need
for dict_item in item_list:
for value in dict_item.values():
if type(value) == dict:
for target_value in value.values():
# do whatever you need with the target_value
print(target_value)
Make sure you also properly format your item_list (see #Kristaps comment).
[Section added after the question was updated]
I got it. So, somehow you get the dictionary embedded in a string.
In this case first thing you need to do is to convert that string to a dictionary. There are a few approaches for this. You can find interesting examples here:
Convert a String representation of a Dictionary to a dictionary?
https://www.geeksforgeeks.org/python-convert-string-dictionary-to-dictionary/
I prepared a little example using ast:
import ast
for dict_item in item_list:
for value in dict_item.values():
try:
# try to evaluate the value; the evaluation might raise some exception
res = ast.literal_eval(value)
if type(res) == dict:
# dictionary found; do whatever you need with it
print(res)
except SyntaxError:
# just continue to the next value
continue

How can I get the Venue ID from the response

Since I just started with Python, I have some difficulties with accessing the keys.
I want to loop through each Foursquare venue I got as an JSON response, to get the Venue ID. The Venue ID then should be added as a parameter to get all the details to the venues.
I already tried it with a for loop, but it did not work:
for a in data['response']['groups']['items']['venue']:
my_place_id = place['id']
venue_ID_resp = requests.get(url=url_venue_details,params=my_place_id)
Error messsage:
for a in data['response']['groups']['items']['venue']:
TypeError: list indices must be integers or slices, not str
The response looks like this:
'response':{
'groups':[
{
'items':[
{
'reasons':{
'count':0,
'items':[
{
'reasonName':'globalInteractionReason',
'summary':'This ' 'spot ' 'is ' 'popular',
'type':'general'
}
]
},
'referralId':'e-0-52bf5eca498e01893b7004fb-0',
'venue':{
'categories':[
{
'icon':{
'prefix':'https://ss3.4sqi.net/img/categories_v2/travel/hostel_',
'suffix':'.png'
},
'id':'4bf58dd8d48988d1ee931735',
'name':'Hostel',
'pluralName':'Hostels',
'primary':True,
'shortName':'Hostel'
}
],
'id':'52bf5eca498e01893b7004fb',
'location':{
I only want to get the Venue ID, like:
print(my_place_id)
4bf58dd8d48988d1ee931234
4bf58dd8d48988d1ee945225
4bf58dd8d48988d1ee931888
4bf58dd8d48988d1ee564563
.
.
.
Your Json contains lists. You can get id:
my_id = data['response']['groups']['items'][0]['venue']['categories'][0]['id']
Note: If you have more elements in your lists, you can create for loop and get all ID.
items inside group in your response JSON is a list. This is the reason you get the error: " TypeError: list indices must be integers or slices, not str" as list index cannot be a string.
As correctly pointed out by #tfw, even groups is a list, so it should be
You need to access it as data['response']['groups'][0]['items'][0]['venue']
If there are going to multiple elements in the items list, then better to loop through them and access like below
for x in data['response']['groups']:
for y in x['items']
print y['venue']

List inside a list - how to access an element

This is my code:
def liveGame(summonerName):
req = requests.get('https://br1.api.riotgames.com/lol/spectator/v3/active-games/by-summoner/' + str(summonerName) + '?api_key=' + apikey)
req_args = json.loads(req.text)
print(req_args)
And this is what I'm receiving from my request.get:
{
'gameId': 1149933395,
'mapId': 11,
'participants': [
{
'teamId': 100,
'spell1Id': 11,
'spell2Id': 4,
'championId': 141,
'profileIconId': 7,
'summonerName': 'Disneyland Party',
...
}
]
}
I've simplified the return of the request, but as you can see the 'participants' index is another list. So, how can I access the contents of this list (teamId, Spell1Id, etc)?
I can only access the full list this way:
print(req_args['participants'])
But, what I want to do is access only one element of the 'participants' list.
I'm using Python 3.6.
You can access this list items using index as you do for normal list
If you want to access first element for req_args['participants'] you can use
req_args['participants'][i]
where i is nothing but the index of item that you want to access from list.
Since items inside linked list are dictionaries to access teamId and spellId of only one item ( in this case first item) you can do following
req_args['participants'][0]['teamId']
req_args['participants'][0]['spell1Id']
you can also iterate over list to access each dictionary and value of teamId, spell1Id or others keys present inside dictionary like this
for participant in req_args['participants']:
print(participant['teamId'])
print(participant['spell1Id'])
this is simple to get value from dictionary object.
print items['participants'][0].get('teamId')
print items['participants'][0].get('spell1Id')

Categories