简体   繁体   中英

How can I get elements from dictionary by key nested in a list?

I have construction like this:

[{
    "meta": {
        "foo": 1, 
        "bar": "string", 
        "baz": "string2"},
    "data": [
        {"id": "1", "quant": 2, "price": 3.14},
        {"id": "2", "quant": 1, "price": 6.66}
    ]
 },
...
]

How can I get elements foo, bar from meta and quant, price from data?

Welcome to SO, We are not code writing services so please post your effort next time you ask question. Refer to the documentation for more information on python Data Sructures.

lists are accessed through index , and Dictionaries are accessed through `keys'

Like _list[index] and _dict['key'] With that basics lets move forward.

l= [{ "meta":{ "foo":1, "bar":"string", "baz":"string2"}, "data":[ {"id":"1", "quant":2, "price":3.14}, {"id":"2", "quant":1, "price":6.66}] } ]

>>> l[0]['meta']['foo']
1
>>> l[0]['meta']['bar']
'string'

>>> l[0]['data'][0]['price']
3.14
>>> l[0]['data'][0]['quant']
2
>>> 

>>> l[0]['data'][1]['quant']
1
>>> l[0]['data'][1]['price']
6.66
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM