从嵌套字典中提取值

2024-05-31 22:50:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我的字典是这样的:

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

正确的方法是什么?你知道吗


Tags: ofthe实体for字典spacemoviequery
3条回答

query是字典而不是列表,所以改为query['fowl']

好吧,你的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'

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

相关问题 更多 >