Python 从嵌套字典中提取值
我的字典是这样的:Python 从嵌套字典中提取值,python,dictionary,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'}]}} 家禽和猴年是其中的两个实体。我试图分别提取这两个实体的所有
query = {'fowl': [{'cateogry': 'Space'}, {'cateogry': 'Movie'}, {'cateogry': 'six'}], u'Year of the Monkey': {'score': 40, 'match': [{'category': u'Movie'}, {'category': 'heaven'}, {'category': 'released'}]}}
家禽
和猴年
是其中的两个实体。我试图分别提取这两个实体的所有类别
值,但运气不佳
这些都不起作用:
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
正确的方法是什么?
query
是一本字典而不是一个列表,因此,你的query
字典不是一个列表,因此你的query
字典是相当时髦的,'foll'
和'Year of the Monkey'
值的结构不同,因此不能使用相同的数据访问模式,也不能将类别拼写为'cateogray'
。如果可以的话,在尝试进一步处理之前最好先修复它
对于提取'foll'
数据:
>>> 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'
嗯,您的
查询
字典相当时髦,例如,'fowl'
和'Year of the Monkey'
值的结构不一样,因此您不能使用相同的数据访问模式,也不能将类别拼写为'cateogray'
。如果可以的话,在尝试进一步处理之前最好先修复它
对于提取'foll'
数据:
>>> 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']
你需要迭代query['Year of the Monkey']['match'][0]['category']
你需要迭代而不是位置,使用键。'category'
是一个拼写错误,请在所有代码都依赖它之前立即修复:)而不是位置,使用密钥。另外,'cateogry'
是一个拼写错误,请在所有代码依赖它之前立即修复:)谢谢,打印查询['Year of the Monkey']['match']
为第二个实体提供了类别。她的实体名称每次都会改变。是否有任何方法可以遍历所有实体并获得类别?谢谢,print query['Year of the Monkey']['match']
为第二个实体提供类别。她的实体名称每次都会改变。是否有任何方法可以遍历所有实体并获得类别?谢谢,print query['Year of the Monkey']['match']
为第二个实体提供类别。她的实体名称每次都会改变。是否有任何方法可以遍历所有实体并获得类别?谢谢,print query['Year of the Monkey']['match']
为第二个实体提供类别。她的实体名称每次都会改变。是否有任何方法可以遍历所有实体并获得这些类别?