从嵌套字典中提取值

时间:2014-11-27 12:01:39

标签: python dictionary

我的字典是这样的:

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

fowlYear of the Monkey是此中的两个实体。我试图分别提取两个实体的所有category值而没有运气。

这些都不起作用:

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

什么是正确的方法?

3 个答案:

答案 0 :(得分:2)

嗯,您的query词典非常时髦,因为'fowl''Year of the Monkey'值的结构不相同,因此您无法使用相同的数据访问模式或类别错误拼写为'cateogry'。如果可以的话,在尝试进一步处理它之前,最好先修复它。

至于提取'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'

答案 1 :(得分:1)

query是字典而非列表,因此请改为query['fowl']

答案 2 :(得分:1)

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