'Json to Python single list of values and Lables
I have a rest API returning a json document. In order to create a chart, I need to extract two list of values.
age_list = [45,46,47,48,.....67] and balance list as
value_list = [3210000,3434700,....13291205]
---- I could print the values, but want to know how to create list of values.
import json
jsonStr = '{"items":[{"age":46,"balance":3210000},{"age":47,"balance":3434700},{"age":48,"balance":3675129},{"age":49,"balance":3932388},{"age":50,"balance":4207655},{"age":51,"balance":4502191},{"age":52,"balance":4817344},{"age":53,"balance":5154559},{"age":54,"balance":5515378},{"age":55,"balance":5901454},{"age":56,"balance":6314556},{"age":57,"balance":6756575},{"age":58,"balance":7229535},{"age":59,"balance":7735602},{"age":60,"balance":8277095},{"age":61,"balance":8856491},{"age":62,"balance":9476446},{"age":63,"balance":10139797},{"age":64,"balance":10849583},{"age":65,"balance":11609053},{"age":66,"balance":12421687},{"age":67,"balance":13291205}],"hasMore":false,"limit":25,"offset":0,"count":22,"links":[{"rel":"self","href":"https://fp7cb75hkszpygo-db202201121316.adb.us-sanjose-1.oraclecloudapps.com/ords/admin/rest-rc1/rc1/45/3000000/0.07"},{"rel":"describedby","href":"https://fp7cb75hkszpygo-db202201121316.adb.us-sanjose-1.oraclecloudapps.com/ords/admin/metadata-catalog/rest-rc1/rc1/45/3000000/item"},{"rel":"first","href":"https://fp7cb75hkszpygo-db202201121316.adb.us-sanjose-1.oraclecloudapps.com/ords/admin/rest-rc1/rc1/45/3000000/0.07"}]}'
pythonObj = json.loads(jsonStr)
for i in pythonObj['items']:
print( '\'',i['age'],'\'',',')
for i in pythonObj['items']:
print( '\'',i['balance'],'\'',',')
Solution 1:[1]
Why do you want to separate the data like this? There's probably a reason that age and balance are coupled. It's generally not a good idea to separate coupled data. For instance, what if you sort the age_list? Then the balances are no longer going to correspond to the ages. If that's not important, then disregard.
You can use a single for loop over the dictionaries in the items list, and accumulate into two lists:
ages = []
balances = []
for dictionary in pythonObj['items']:
ages.append(dictionary['age'])
balances.append(dictionary['balance'])
This is called the accumulator pattern and is ubiquitous in programming. I recommend checking out the official Python tutorial to familiarize yourself with the basics of the language.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ddejohn |
