简体   繁体   中英

Extracting value from nested dictionary

My dictionary is like this:

query =  {'fowl': [{'cateogry': 'Space'}, {'cateogry': 'Movie'}, {'cateogry': 'six'}], u'Year of the Monkey': {'score': 40, 'match': [{'category': u'Movie'}, {'category': 'heaven'}, {'category': 'released'}]}}

fowl and Year of the Monkey are two entities in this. I am trying to extract all category values for both entities separately with no luck.

None of these work:

query[0] # I was expecting values for fowl
query[0]['category'] # I was expecting all category for fowl but seems wrong
query[0]['category'][0] # category space for fowl

what is the correct approach?

Well, your query dictionary is rather funky, for one, 'fowl' and 'Year of the Monkey' values are not structured the same, so you cannot aply the same data access patterns, or categories being misspelled as 'cateogry' . If you can, you may be better off fixing that before trying to process it further.

As for extracting the 'fowl' data:

>>> query =  {'fowl': [{'cateogry': 'Space'}, {'cateogry': 'Movie'}, {'cateogry': 'six'}], u'Year of the Monkey': {'score': 40, 'match': [{'category': u'Movie'}, {'category': 'heaven'}, {'category': 'released'}]}}

>>> query['fowl'] # 'fowl'
[{'cateogry': 'Space'}, {'cateogry': 'Movie'}, {'cateogry': 'six'}]

>>> [d['cateogry'] for d in query['fowl']] # 'fowl' categories
['Space', 'Movie', 'six']

>>> [d['cateogry'] for d in query['fowl']][0] # 'fowl' 'Space' category
'Space'

query是字典而不是列表,所以请使用query['fowl']代替

query['Year of the Monkey']['match'][0]['category']您需要迭代

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