Reputation: 49
I have some json that I have converted to a list in Python like this:
jsonText = '[{"stationID":"ABCD1234","obsTimeUtc":"2021-05-04T11:53:04Z","obsTimeLocal":"2021-05-04 21:53:04","neighborhood":"HelloWorld","softwareType":"SoftwareHelloWorld","country":"Hello","solarRadiation":0.0,"lon":1234.1234,"realtimeFrequency":null,"epoch":12345678,"lat":1234.1234,"uv":0.0,"winddir":1234,"humidity":1234,"qcStatus":1,"imperial":{"temp":57,"heatIndex":57,"dewpt":56,"windChill":57,"windSpeed":0,"windGust":0,"pressure":29.95,"precipRate":0.07,"precipTotal":0.21,"elev":56}}]'
listText = js.loads(jsonText)
print('--NEW FORMAT--')
print(listText)
Which returns this list:
[{'stationID': 'ABCD1234', 'obsTimeUtc': '2021-05-04T11:53:04Z', 'obsTimeLocal': '2021-05-04 21:53:04', 'neighborhood': 'HelloWorld', 'softwareType': 'SoftwareHelloWorld', 'country': 'Hello', 'solarRadiation': 0.0, 'lon': 1234.1234, 'realtimeFrequency': None, 'epoch': 12345678, 'lat': 1234.1234, 'uv': 0.0, 'winddir': 1234, 'humidity': 1234, 'qcStatus': 1, 'imperial': {'temp': 57, 'heatIndex': 57, 'dewpt': 56, 'windChill': 57, 'windSpeed': 0, 'windGust': 0, 'pressure': 29.95, 'precipRate': 0.07, 'precipTotal': 0.21, 'elev': 56}}]
However I don't want the keys in the list (stationID:. obsTimeUtc: etc.), only the values so that it would look more like this:
[["ABCD1234","2021-05-04T11:53:04Z","2021-05-04 21:53:04","HelloWorld","SoftwareHelloWorld","Hello",0.0,1234.1234,"null",12345678,1234.1234,0.0,1234,1234,1,57,57,56,57,0,0,29.95,0.07,0.21,56]]
How do I remove the "keys" in the list and just keep the values?
Upvotes: 0
Views: 504
Reputation: 375
def listFromDict(d):
resultList = []
for k in d.keys():
if isinstance(d[k], dict):
resultList.extend(listFromDict(d[k]))
else:
resultList.append(d[k])
return resultList
result = []
for e in listText:
result.append(listFromDict(e))
print(result)
Upvotes: 1
Reputation: 23624
I would do it with a list comprehension. This will handle the case when there are multiple dicts in the list structure:
data = [list(d.values()) for d in listText]
To handle recursive dicts I would use a generator:
def flatten(listText):
def _flatten(item):
if isinstance(item, dict):
for value in item.values():
yield from _flatten(value)
else:
yield item
return [list(_flatten(d)) for d in listText]
Upvotes: 1