2017-01-09 85 views
-2

我没有经验与Python,我试图直接从嵌套字典中查询键值。我用下面的工作:获取深入嵌套的键值,而无需for循环Python

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

我能得到什么,我需要用for loop,但是如果我知道,关键是直接点名sugar哪能.get()呢?当你已经知道你想要什么时,使用for loop似乎是浪费的周期。

编辑:我查询DynamoDB表和我得到的响应是在字典形式。我的搜索查询是results=client.query(**allmyargs),所以如果我没有弄错,我的字典的名字就是结果。

当我尝试results['Items']['Ingredients']['M']['sugar']时出现错误list indices must be integers, not str

最终编辑:我有很多要学习。

+2

'OBJ [ '物品'] [ '成分'] [ 'M'] [ '糖']'? – RomanPerekhrest

+2

只需直接访问密钥? '数据[ '相关'] [ '成分'] [ 'M'] [ '糖']'。你会用什么循环? –

+2

OP,这是字典的全部内容; *如果您知道密钥,您可以获取值*。没有循环,没有任何东西。 –

回答

1

您的实际响应对象有不同的结构比你张贴的例子,这意味着它不可能给用于访问数据的准确方法。

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)) 
+0

WISHARD MISTER'f!万分感谢,男士。我没有足够的信誉来充分感谢你的指导和帮助。这就像一个魅力。非常感激! – AppleBaggins

+0

@AppleBaggins不用客气。如果答案已经解决了你的问题,那么堆栈溢出的方式来感谢某人[接受它作为答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-工作),即使你不能在答案上投票,你也可以做到这一点:)这也给了你一些声誉和信号给别人,而不是现在解决的问题。 – roganjosh

+0

完成!感谢您使我的第一篇文章富有成果和教育! – AppleBaggins

0
import requests 
import json 
r ="""{ 
"Items": { 
    "Ingredients": { 
    "M": { 
     "sugar": { 
     "S": "three quarters of a cup" 
}}}}}""" 
j = json.loads(r) 


print j['Items']['Ingredients']["M"]["sugar"] 

输出

{u'S': u'three quarters of a cup'} 
+0

谢谢!有没有办法做到这一点,而无需导入更多模块或库? – AppleBaggins

+0

要么你需要使用循环或图书馆 – Shijo