在Python中不使用for循环获取深层嵌套的键值

时间:2017-01-09 17:03:31

标签: python json dictionary

我没有Python经验,而且我试图直接从嵌套字典中查询键值。我正在使用以下内容:

"Items": {
  "Ingredients": {
    "M": {
      "sugar": {
        "S": "three quarters of a cup"

我可以使用for loop获得我需要的内容,但如果我知道该密钥名为sugar,我该怎样直接.get()呢?当你已经知道你想要什么时,使用for loop似乎是浪费的周期。

编辑:我正在查询DynamoDB表,我得到的响应是dict格式。我的搜索查询为results=client.query(**allmyargs),因此,如果我没有弄错的话,我的字典名称就是结果。

当我尝试results['Items']['Ingredients']['M']['sugar']时,我收到list indices must be integers, not str

的错误

最终编辑:我需要学习很多东西。

1 个答案:

答案 0 :(得分:1)

您的实际响应对象的结构与您发布的示例不同,这意味着无法提供准确的方法来访问数据。

JSON和嵌套列表+ dicts很难阅读。一种方法是复制/粘贴到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))
相关问题