简体   繁体   English

控制台中的KeyError,但是键存在并且功能正常

[英]KeyError in console, but key exists and function works fine

I have looked at all the other keyerror questions on here, but I couldn't find one that addressed my situation. 我在这里查看了所有其他关键错误问题,但找不到适合我情况的问题。 I am pulling location information from Google and reading the json info into a python list. 我正在从Google提取位置信息,并将json信息读取到python列表中。 Here is the part of the script that goes iterates over the results from Google. 这是脚本的一部分,可以迭代Google的结果。

results = []

# def get_data():
for term, (latitude, longitude, search_radius) in search_parameters.items():
    params = {
        'query': term,
        'location': (latitude, longitude),
        'radius': search_radius
    }
    geocode_result = gmaps.places(**params)
    for i in geocode_result['results']:

        results.append(i['name'])
        results.append(i['geometry']['location']['lat'])
        results.append(i['geometry']['location']['lng'])
        results.append(i['formatted_address'])
        results.append(i['opening_hours']['open_now'])
        results.append(i['price_level'])
        results.append(i['rating'])
        results.append(i['types'])

    if 'next_page_token' in geocode_result.keys():
        while 'next_page_token' in geocode_result.keys():
            time.sleep(2.5)
            params.update({'page_token': geocode_result['next_page_token']})
            geocode_result = gmaps.places(**params)
            for i in geocode_result['results']:
                results.append(i['name'])
                results.append(i['geometry']['location']['lat'])
                results.append(i['geometry']['location']['lng'])
                results.append(i['formatted_address'])
                results.append(i['opening_hours']['open_now'])
                results.append(i['price_level'])
                results.append(i['rating'])
                results.append(i['types'])
    else:
        break

    print(results)

Here is an example of the json style python code that it is pulling from. 这是从中提取的json样式python代码的示例。

[{
  'html_attributions': [],
  'next_page_token': 'CpQCBgEAAFzW9_qpkvmXV8sFiwXg6dEp2jsZXEqQOO4upW1U0FZPK0kiJvSmEbx4EuhAtDD4vtJcC4duqCj6oo0P68cRkGArenzZQWr61Wne0vA44R16SrfCDWLxQjqUu8zUcdLvdB7HfOHPMd7-KWK4cmX-6bLYIJldmnJBeqhnR5xmtB_TGlMyGlzh4vZ4kOB8dc1bnD6ijWxfFyz8wJ1ugA_5hZHLXtCY6NkE8TVYgTTV9710puKlKgiVSSkjwV3IsGgEhzixzGRrVHg2dB3Ehv2KHRuXnvIQJHr-CIkUoK79vI-45pyitdYlW1h9UQk_fzDsIeec3PNE5Qz6kN--NcDv-_jzFBr7QS2RGLkAcZX4aFdfEhCoP3MAVgjsl_tKdYaIX8y_GhSvCFZSxLfWVDAyF--7T6l32G0YFw',
  'results': [{
    'formatted_address': '2222 McKinney Ave, Dallas, TX 75201, United States',
    'geometry': {
      'location': {
        'lat': 32.7935,
        'lng': -96.8021119
      },
      'viewport': {
        'northeast': {
          'lat': 32.7948813802915,
          'lng': -96.8009040197085
        },
        'southwest': {
          'lat': 32.7921834197085,
          'lng': -96.8036019802915
        }
      }
    },
    'icon': 'https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png',
    'id': '26ba45975d09c8889ea321078b6bf10ceff07359',
    'name': 'Smashburger',
    'opening_hours': {
      'open_now': True,
      'weekday_text': []
    },
    'photos': [{
      'height': 3024,
      'html_attributions': ['<a href="https://maps.google.com/maps/contrib/107709113475800121508/photos">Terry Wint Jr</a>'],
      'photo_reference': 'CmRaAAAA9BPb8sP5KUp9bLAgSd9dPQzH15TkG3sw5T6qOa-WSV1hi-3DLIhVzWI5woD2GtSl3aktKXTXktLUfr9vpum-XywbqFMKunee-YhWwPtwOGJaO5lULU-g1px7Z6lPUFvqEhDrofF3_89I455YRKo2hZuFGhRilVDqXdt5x2jPieN3W07UvJwsvA',
      'width': 4032
    }],
    'place_id': 'ChIJ22Ci9y-ZToYRDw1hkXkjceY',
    'price_level': 1,
    'rating': 4.1,
    'reference': 'CmRSAAAAzQIvy0nuhTQpRoAFTlilcVY_BfqGFj7gNlpNeIecwOWGV1x0qFm80zkPYFYKtJ15ilHYSoQbDH2wsQ_vahw5ilhriHA0EBWavcyev4mYVgNWssL0neY5d7YwOLAgtSEvEhBN6e_DakrfQPVtqkagEtQ4GhRCdi5cZ6CKfk6AqXkuGJ9ZVpuR-A',
    'types': ['restaurant', 'food', 'point_of_interest', 'establishment']
  }, 

I am getting this traceback error in terminal when i run it, but when I print my results everything is returning with no issues. 我在运行终端时遇到此追溯错误,但是当我打印结果时,一切都返回没有问题。

Traceback (most recent call last):
  File "testing.py", line 52, in <module>
    results.append(i['price_level'])
KeyError: 'price_level'

Actually "price_level" is outside of the list. 实际上,“ price_level”不在列表中。

You'll have it with geocode_result['price_level'] 您将使用geocode_result['price_level']拥有它

keys in json file have to be double quoted - in my honest opinion. json文件中的键必须用双引号引起来-诚实地说。

"In JSON, keys must be strings, written with double quotes" from here : https://www.w3schools.com/js/js_json_syntax.asp 来自此处的“在JSON中,键必须是用双引号写成的字符串”: https : //www.w3schools.com/js/js_json_syntax.asp

As a few people have pointed out, directly and indirectly, I should start a new ticket for the issue that I am facing. 正如一些人指出的那样,我应该直接和间接地为我面临的问题开一张新票。 The issue is that the value that I was calling 'price_level' is not a key in 'geocode_result' . 问题是,我在呼唤值'price_level'是不是一个关键的'geocode_result' Some how I was still able to get the values from calling it, but the keyerror was triggered post-output. 我仍然可以通过调用它来获取值,但是在输出后触发了keyerror。 Now I have to figure out how to turn 'price_level ' into a key. 现在,我必须弄清楚如何将'price_level ”转换为密钥。

Thank you all for your help in figuring this out. 谢谢大家为解决这个问题所提供的帮助。

Turns out the issue was that not all of the responses being fed back contained all the key's that I was calling. 事实证明,并不是所有反馈的响应都包含我正在调用的所有密钥。 That is why it would run for what seemed like the entire script, and then stop when the keyerror was raised towards the end. 这就是为什么它将在看起来像整个脚本的情况下运行,然后在出现关键错误时将其停止的原因。 I'm going to add a try statement to the for loop section. 我要在for循环部分添加一个try语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM