简体   繁体   English

从嵌套字典中提取值

[英]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. fowlYear of the Monkey是这两个实体。 I am trying to extract all category values for both entities separately with no luck. 我试图没有运气分别提取两个实体的所有category值。

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' . 好吧,您的query字典相当时髦,因为'fowl''Year of the Monkey'值结构不同,因此您无法使用相同的数据访问模式,或者将类别拼写为'cateogry' If you can, you may be better off fixing that before trying to process it further. 如果可以的话,在尝试进一步处理之前,最好将其修复。

As for extracting the 'fowl' data: 至于提取'fowl'数据:

>>> 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']您需要迭代

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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