如何在Python中访问字典值

时间:2013-04-18 13:43:12

标签: python python-2.7

请帮助我访问字典值:

result = {
    u'responseData': {
        u'cur': {
            u'moreResults': u'myresulthere', 
            u'ResultCount': u'4',
            u'Time': u'0.10',
            u'Count': u'4', 
            u'page': [{u'start': u'0', u'label': 1}], 
            u'currentIndex': 0
        },

        u'results': [{u'GClass': u'Gch', 
                      u'visible': u'slobaexper',
                      u'Formatting': u'Slobog'
                     }]
    }, 

    u'reDetails': None,
    u'restatus': 200
}

我想访问“结果”值。 当我这样做时:

print 'results' in result.keys()

即使它存在,也会打印错误

当我这样做时:

def GPlag(text,encode=False):
import urllib, urllib2, json
if encode == True:
    text = text.encode('utf-8')
query = urllib.quote_plus(text)
base_url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q='
url = base_url + '%22' + query + '%22'
request = urllib2.Request(url,None)
response = urllib2.urlopen(request)
result = json.load(response)
output = []
if result['responseData']['results'] != []:
    firstMatch = result['responseData']['results'][0]
    output.append(firstMatch['title'])
    output.append(firstMatch['visibleUrl'])
    output.append(firstMatch['content'])
return output

def callGPlag(n):
    for s in n:
        outcome = GPlag(s,encode=True)

它提供 TypeError:'NoneType'对象没有属性'_ getitem _' 在此if result['responseData']['results']

1 个答案:

答案 0 :(得分:1)

results位于Data内。

print result['Data']['results']
print 'results' in result['Data']