控制台中的KeyError,但是键存在并且功能正常 [英] KeyError in console, but key exists and function works fine

查看:292
本文介绍了控制台中的KeyError,但是键存在并且功能正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里查看了所有其他关键错误问题,但是找不到适合我情况的问题.我正在从Google提取位置信息,并将json信息读取到python列表中.这是脚本中遍历Google结果的部分.

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. Here is the part of the script that goes iterates over the results from 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)

这是从中提取的json样式python代码的示例.

Here is an example of the json style python code that it is pulling from.

[{
  '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'

推荐答案

正如一些人指出的那样,我应该直接或间接地为我所面临的问题开一张新票.问题是我正在调用'price_level'的值不是'geocode_result'中的键.我仍然可以通过调用它来获取值的一些方式,但是keyerror在输出后触发.现在,我必须弄清楚如何将'price_level'转换为密钥.

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'. Some how I was still able to get the values from calling it, but the keyerror was triggered post-output. Now I have to figure out how to turn 'price_level' into a key.

感谢大家为您解决问题提供帮助.

Thank you all for your help in figuring this out.

原来的问题是,并非所有反馈的响应都包含我正在调用的所有密钥.这就是为什么它将在看起来像整个脚本的情况下运行,然后在出现关键错误时将其停止的原因.我要在for循环部分添加一个try语句.

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.

这篇关于控制台中的KeyError,但是键存在并且功能正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆