您的实际响应对象有不同的结构比你张贴的例子,这意味着它不可能给用于访问数据的准确方法。
JSON和嵌套列表+字典很难阅读。一种方法是复制/粘贴到jsonlint.com并“验证”。尽管python对象会失败,但它更易于阅读。我觉得这比打印更快,但这也是一个选择。
根据您的澄清意见:
results = {u'Count': 1, u'Items': [{
u'Ingredients': {
u'M': {
u'MacIntosh apples': {
u'S': u'six cups'
},
u'flour': {
u'S': u'two tablespoons'
},
u'sugar': {
u'S': u'three quarters of a cup'
},
u'lemon juice': {
u'S': u'one tablespoon'
},
u'nutmeg': {
u'S': u'one eighth of a teaspoon'
},
u'cinnamon': {
u'S': u'three quarters of a teaspoon'
},
u'salt': {
u'S': u'one quarter of a teaspoon'
}
}
}
}], u'ScannedCount': 1
}
# First get one of the inner dictionaries
ingredients = results['Items'][0]['Ingredients']['M']
# List of ingredients you are looking for
ingredients_wanted = ['sugar', 'flour', 'nutmeg', 'salt']
# Convert list to a set for faster lookups (not absolutely necessary, especially for small lists)
ingredients_wanted = set(ingredients_wanted)
amount_list = []
for ingredient, amount in ingredients.items():
if ingredient in ingredients_wanted:
print('Ingredient: {} \t in amount: {}'.format(ingredient, amount['S']))
print('\n')
# Or directly without iterating the whole thing
for item in ingredients_wanted:
amount = ingredients[item]['S']
print('Ingredient: {} \t in amount: {}'.format(item, amount))
'OBJ [ '物品'] [ '成分'] [ 'M'] [ '糖']'? – RomanPerekhrest
只需直接访问密钥? '数据[ '相关'] [ '成分'] [ 'M'] [ '糖']'。你会用什么循环? –
OP,这是字典的全部内容; *如果您知道密钥,您可以获取值*。没有循环,没有任何东西。 –