Reputation: 45
I need to access structured data in a nested way but I didn't understand how to do it.
The data is structured in this way:
{'function':'data_chip',
'group_id': 172,
'Types': [
{'TMS0202':'SR-20',
'TMS0207':'SR-22',
'TMS0201': 'TI-4000',
'TMS0203': 'TI-450'
}
]
}
Upvotes: 0
Views: 60
Reputation: 21
to access nested data you could using
data['keyword']
or data.get('keyword', default value)
In your case that you want information on types (I assumed you want all data) you could looping on types, using something like:
datas = {'function':'data_chip',
'group_id': 172,
'Types': [
{'TMS0202':'SR-20',
'TMS0207':'SR-22',
'TMS0201': 'TI-4000',
'TMS0203': 'TI-450'
}
]
}
for data in datas['types']:
put your code here
Upvotes: 0
Reputation: 2902
Is there a particular part you're trying to access?
Here are a few examples:
$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> data = {'function':'data_chip',
... 'group_id': 172,
... 'Types': [
... {'TMS0202':'SR-20',
... 'TMS0207':'SR-22',
... 'TMS0201': 'TI-4000',
... 'TMS0203': 'TI-450'
... }
... ]
... }
>>> data['function']
'data_chip'
>>> data['Types'][0]['TMS0202']
'SR-20'
>>> data['group_id']
172
Upvotes: 1
Reputation: 3515
To access the top-level data, use a single dictionary index:
data['function'] —> 'data chip'
To access the data in the Types
key, you need to access the list first then the dictionary inside it:
data['Types'][0]['TMS0202'] —> 'SR-20'
Each time you get a level deeper, consider what data type you now need to access. If it is a dict
you need the keys, if it is a list
you need the integer index. Each level you access is another retrieval using square brackets:
data[key][index][key]
Upvotes: 1