I have a JSON file that looks like this (shortened):
data = {
"station": [
{
"key": "105285",
"name": "Borlänge Sol",
"owner": "SMHI",
"ownerCategory": "CLIMATE",
"measuringStations": "CORE",
"from": 536457600000,
"to": 1664719200000,
"height": 168.0,
"latitude": 60.4878,
"longitude": 15.4297,
"value": [{"date": 1664719200000, "value": "0", "quality": "Y"}],
},
{
"key": "71415",
"name": "Göteborg Sol",
"owner": "SMHI",
"ownerCategory": "CLIMATE",
"measuringStations": "CORE",
"from": 1286409600000,
"to": 1664719200000,
"height": 84.824,
"latitude": 57.6879,
"longitude": 11.9796,
"value": [{"date": 1664719200000, "value": "1429", "quality": "Y"}],
},
{
"key": "68545",
"name": "Hoburg Sol",
"owner": "SMHI",
"ownerCategory": "CLIMATE",
"measuringStations": "CORE",
"from": 1352991600000,
"to": 1664719200000,
"height": 36.0,
"latitude": 56.921,
"longitude": 18.1506,
"value": [{"date": 1664719200000, "value": "0", "quality": "Y"}],
},
{
"key": "65075",
"name": "Karlskrona Sol",
"owner": "SMHI",
"ownerCategory": "CLIMATE",
"measuringStations": "CORE",
"from": 1246406400000,
"to": 1664719200000,
"height": 10.0,
"latitude": 56.1091,
"longitude": 15.587,
"value": [{"date": 1664719200000, "value": "3586", "quality": "Y"}],
},
{
"key": "178985",
"name": "Tarfala Sol",
"owner": "SMHI",
"ownerCategory": "CLIMATE",
"measuringStations": "CORE",
"from": 1167609600000,
"to": 1664719200000,
"height": 1144.0,
"latitude": 67.9123,
"longitude": 18.6101,
"value": None,
},
]
}
I want to make a list of the values which are inside 'value'
, i.e [0, 1429, 0, 3586]
,
I tried this but it's returning an error:
value_dict = [data['station'][i]['value']['value'] for i in range(len(data['station'])) if data['station'][i]['value'][0]['value'] is not None]
How can I access those values? Also is this the right way to ignore NoneType values (such as the last one)?
CodePudding user response:
You can get values like this,
In [1]: [item.get('value')[0].get('value') for item in data['station']]
Out[1]: ['0', '1429', '0', '3586']
You can user filter
to ignore the None
values,
list(filter(None, [item.get('value')[0].get('value') for item in data['station']]))
CodePudding user response:
if value
contains only one element
value_dict = [data['station'][i]['value'][0]['value'] for i in range(len(data['station']))]
or if contains more than 1
value_dict = [[data['station'][i]['value'][j]['value'] for j in range(len(data['station'][i]['value']))] for i in range(len(data['station']))]
CodePudding user response:
Get the "station"
key first and iterate through the list of dictionaries. Get the "value"
key and check if it's not None
. Then it should be a list of single dictionary. Get it's item and then it's "value"
key:
result = []
for d in data["station"]:
value = d["value"]
if value is not None:
result.append(value[0]["value"])
print(result)