Get parent keys in a nested dictionary - python

I looked through some other answers but I don't fully understand. There are no duplicate values.
{
"type": "champion",
"data": {
"89": {
"title": "the Radiant Dawn",
"name": "Leona"
},
"110":{
"title": "the Arrow of Retribution",
"name": "Varus"
}
}
}
what I have, I'm not sure how to proceed. In the actual dict there's more information than just title and key
championID = 0
for key, value in championData["data"].items():
for childkey,childvalue in value.items():
#
champion = getChamp(championID)
I want to input a name and have it return the ID (the number, 89 and 110 are listed). For example, inputting Leona would return 89.
(Sorry, I could have done a better job of asking the question at the beginning :'v)

This will work:
championData = {"type": "champion", "data": {
"89": {
"title": "the Radiant Dawn",
"name": "Leona"
},
"110": {
"title": "the Arrow of Retribution",
"name": "Varus"
}
}}
name = "Leona"
data = championData['data']
for championId in data:
if(data[championId]['name']) == name:
print(championId)
The output is: 89

Related

How to print more than one value from nested dict in Python

I am trying to parse output from Get API. My response text is:
{
"data": [
{
"date_created": "22:20:47",
"name": "test1",
"id": "12345",
"status": "0"
},
{
"date_created": "00:09:17",
"name": "test2",
"id": "23456",
"status": "0"
},
{
"date_created": "00:08:02",
"name": "test3",
"id": "34567",
"status": "0"
},
I have ~100 ids. I need to print only ids and search for specific id from list.
so far, i parse with next method:
json_data = get_req.text
python_data = json.loads(json_data)
id = python_data["data"][0]["id"]
print "Object id: ", id
But it is printing only one ID, where i need all of them.
Do you have any ideas how can i print all of them?
Try using this below code snippet:
for i in range(len(python_data["data"])):
print(python_data["data"][i]["id"])
I got the expected output :
12345
23456
34567
you have a list of dicts so you need loop:
ids = [x.get('id') for x in python_data["data"]]
print (ids)

Python - check if variable is == to json element and print

I have a json response with thousands of student information bits. It looks like this:
{
"users": [
{
"agents": [
{
"href": "private url here",
"sourcedId": "g560",
"type": "user"
}
],
"dateLastModified": "2016-10-24T15:24:00.000Z",
"demographics": {
"href": "private url here",
"sourcedId": "s557",
"type": "demographics"
},
"email": "example#example.com",
"familyName": "Smith",
"givenName": "John",
"identifier": "000000000",
"metadata": {
"ext_grade_level": "11"
},
"orgs": [
{
"href": "private URL here",
"sourcedId": "000000000000000000000000000000",
"type": "org"
},
{
"href": "private URL Here",
"sourcedId": "0000000000000000000000000000000000",
"type": "org"
},
{
"href": "private url here",
"sourcedId": "000000000000000000000000000",
"type": "org"
}
],
"role": "student",
"sourcedId": "s557",
"status": "active",
"username": "000000000"
},
{
That then repeats starting with "agents": [ for the next student, approximately 2,500 times. What I'm really looking to do is the following, I have "students_data" = students_data.json().
json1 = students_data['users']
stu_email = input("Enter a student email address here:")
if item in json1 == stu_email:
print(stu_email)
When I run that, nothing happens. It asks for an input and then just ends. No errors, no nothing. I have nothing to go off, other than it's obviously wrong. Also, if it did work, how would I then print the familyName, givenName, and identifier for the matching address?
The list nested in the dictionaries really messes me up, because the only way I know how to deal with lists is by indexing with [0] or [1] etc. however, that isn't an option in this case.
Also, I tried doing json1['email'] but I get the "TypeError: list indices must be integers or slices, not str" which I assume is because I'm skipping over the list.
Thanks for any help!
Json data can consist of dictionaries and lists nested within each other. Here we loop through the list student_data['users'] to look for the first student with a matching email.
student_email = input("Enter a student email address here:")
for student in students_data['users']:
if student['email'] == student_email:
print('found a match')
print(student)
break
else:
print('no match found')

How to iterate over this embedded JSON "list" in python?

New to python here. I'm trying to iterate over all the JSON "group" objects for each person but having some difficulty. This is only a partial list (not all users have groups) so I need to use the try/catch block so users without a list of groups don't cause early termination.
The JSON data snippet:
{
"people": [
{
"person": {
"name": "joe",
"email": "joe#foo.net",
"groups": [
{
"name": "office",
"id": 23
},
{
"name": "mfg",
"id": 93
} ]
},
"person": {
"name": "bill",
"email": "bill#foo.net",
"groups": [
{
"name": "acctg",
"id": 133
},
{
"name": "mgr",
"id": 207
} ]
}
}
]
}
This is my code so far:
jdata = json.loads...
for person in jdata['people']:
for key, val in person.iteritems():
print "key ", key , " is ", val
print val["name"]
print val["email"]
try:
for gkey, gval in val["groups"][0].iteritems():
print "gval: " + gval
except:
foo=1
Notice I can print out a list of the 0th item in the group list by doing the for gkey...val["groups"][0].iteritems() but what I really want is iterate over all the group lists of each person entry (some people belong to two groups, others 10 or more) so there is no fixed length. How can I do this?
Is that what you want? :
>>> for group in j['people'][0]['person']['groups']:
for k,v in group.items():
print(k,v)
name acctg
id 133
name mgr
id 207
Or more generally:
>>> for person in j['people']:
for group in person['person']['groups']:
print('Name : {} --- ID: {}'.format(group['name'], group['id']))
Name : acctg --- ID: 133
Name : mgr --- ID: 207

Flask python json parsing

Hello I am completely new to flask and python. I am using an API to geocode
and i get a json which is
"info": {
"copyright": {
"imageAltText": "\u00a9 2015 MapQuest, Inc.",
"imageUrl": "http://api.mqcdn.com/res/mqlogo.gif",
"text": "\u00a9 2015 MapQuest, Inc."
},
"messages": [],
"statuscode": 0
},
"options": {
"ignoreLatLngInput": false,
"maxResults": -1,
"thumbMaps": true
},
"results": [
{
"locations": [
{
"adminArea1": "US",
"adminArea1Type": "Country",
"adminArea3": "",
"adminArea3Type": "",
"adminArea4": "",
"adminArea4Type": "County",
"adminArea5": "",
"adminArea5Type": "City",
"adminArea6": "",
"adminArea6Type": "Neighborhood",
"displayLatLng": {
"lat": 33.663512,
"lng": -111.958849
},
"dragPoint": false,
"geocodeQuality": "ADDRESS",
"geocodeQualityCode": "L1AAA",
"latLng": {
"lat": 33.663512,
"lng": -111.958849
},
"linkId": "25438895i35930428r65831359",
"mapUrl": "http://www.mapquestapi.com/staticmap/v4/getmap?key=&rand=1009123942",
"postalCode": "",
"sideOfStreet": "R",
"street": "",
"type": "s",
"unknownInput": ""
}
],
"providedLocation": {
"city": " ",
"postalCode": "",
"state": "",
"street": "E Blvd"
}
}
]
}
RIght now i am doing this
data=json.loads(r)
return jsonify(data)
and this prints all the data as shown above. I need to get the latlng array from locations which is in results. I have tried
data.get("results").get("locations") and hundreds of combinations like that but i still cant get it to work. I basically need to store the lat and long in a session variable. Any help is appreciated
Assuming you just have one location as in your example:
from __future__ import print_function
import json
r = ...
data = json.loads(r)
latlng = data['results'][0]['locations'][0]['latLng']
latitude = latlng['lat']
longitude = latlng['lng']
print(latitude, longitude) # 33.663512 -111.958849
data.get("results") will return a list type object. As list object does not have get attribute, you can not do data.get("results").get("locations")
According to the json you provided, you can do like this:
data.get('results')[0].get('locations') # also a list
This will give you the array. Now you can get the lat and lng like this:
data.get('results')[0].get('locations')[0].get('latLng').get('lat') # lat
data.get('results')[0].get('locations')[0].get('latLng').get('lng') # lng
I summarize my comments as follows:
You can use data as a dict of dict and list.
A quick ref to dict and list:
A dictionary’s keys are almost arbitrary values.
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
official docs about stdtypes

output every attribute, value in an uneven JSON object

I have a very long and uneven JSON object and I want to output every attribute, value for the end points (leaves) of the object.
For instance, it could look like this:
data = {
"Response": {
"Version": "2.0",
"Detail": {
"TransactionID": "Ib410c-2",
"Timestamp": "04:00"
},
"Transaction": {
"Severity": "Info",
"ID": "2222",
"Text": "Success"
},
"Detail": {
"InquiryDetail": {
"Value": "804",
"CountryISOAlpha2Code": "US"
},
"Product": {
"ID": "PRD",
"Org": {
"Header": {
"valuer": "804"
},
"Location": {
"Address": [
{
"CountryISOAlpha2Code": "US",
"Address": [
{
"Text": {
"#Value": 2,
"$": "Hill St"
}
}
]
}
]
}
}
}
}
}
}
I want to output each potential leaf. It can output the (final attribute or the entire path) and the value.
I know I just need to add something to this:
data = json.loads(inputFile)
small = repeat(data)
for attribute,value in small.iteritems():
print attribute,value
You could use recursion:
def print_leaf_keyvalues(d):
for key, value in d.iteritems():
if hasattr(value, 'iteritems'):
# recurse into nested dictionary
print_leaf_keyvalues(value)
else:
print key, value
Demo on your sample data:
>>> print_leaf_keyvalues(data)
Version 2.0
valuer 804
Address [{'CountryISOAlpha2Code': 'US', 'Address': [{'Text': {'#Value': 2, '$': 'Hill St'}}]}]
ID PRD
CountryISOAlpha2Code US
Value 804
Text Success
Severity Info
ID 2222
This will not handle the list value of Address however. You can always add an additional test for sequences and iterate and recurse again.

Categories