键在字典中时出现键错误 [英] Key Error when key is in dictionary

查看:122
本文介绍了键在字典中时出现键错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是试图从一堆照片上的EXIF数据中提取一些经纬度信息,但是即使稍后(成功)使用该键打印特定坐标,代码也会抛出KeyError.

Just trying to pull some lat/lon info from EXIF data on a bunch of photos, but code is throwing a KeyError even though that key is used (successfully) later on to print specific coordinates.

有问题的词典是"tags"-'GPS GPSLatitude''GPS GPSLongitude'都是tags.keys()中的键;我已经三重检查了.

Dictionary in question is "tags" - 'GPS GPSLatitude' and 'GPS GPSLongitude' are both keys in tags.keys(); I've triple checked.

因此,对于为什么tags['GPS GPSLatitude']& tags['GPS GPSLongitude']抛出关键错误?

So any intuition on why tags['GPS GPSLatitude'] & tags['GPS GPSLongitude'] are throwing key errors?

import os
import exifread

output = dict()
output['name'] = []
output['lon'] = []
output['lat'] = []

for file in os.listdir(path):
    if file.endswith(".JPG"):
        full_path = path + file
        print (file) #check to ensure all files were found
        output['name'].append(file) #append photo name to dictionary
        f = open(full_path, 'rb') #open photo
        tags = exifread.process_file(f) #read exifdata
#       lon = tags['GPS GPSLongitude'] #this + next line = one method
#       output['lon'].append(lon)
#       output['lat'].append(tags['GPS GPSLatitude']) # = cleaner second method
        for tag in tags.keys():
            if tag in ('GPS GPSLongitude','GPS GPSLatitude'):
                print ("Key: %s, value %s" % (tag, tags[tag])) #successfully prints lat/lon coords with 'GPS GPSLongitude' and 'GPS GPSLatitude' as keys

更新:

这是print (tags.keys())的输出-您将在其中看到GPS GPSLatitudeGPS GPSLongitude.另外,请手动检查我正在使用的子集中的所有照片是否具有GPS数据.

Here's the output of print (tags.keys()) -- you'll see GPS GPSLatitude and GPS GPSLongitude in there. Also, have manually checked all the photos in the subset I'm using have GPS data.

dict_keys(['GPS GPSImgDirection', 'EXIF SceneType', 'MakerNote Tag 0x0006', 'GPS GPSDestBearing', 'Thumbnail XResolution', 'EXIF BrightnessValue', 'GPS GPSAltitude', 'GPS GPSLongitude', 'EXIF LensSpecification', 'GPS GPSAltitudeRef', 'GPS GPSSpeedRef', 'GPS GPSDestBearingRef', 'EXIF WhiteBalance', 'Thumbnail ResolutionUnit', 'EXIF FocalLengthIn35mmFilm', 'EXIF SceneCaptureType', 'Image Model', 'MakerNote Tag 0x0008', 'Image Make', 'EXIF ShutterSpeedValue', 'MakerNote Tag 0x0007', 'EXIF ExifImageWidth', 'EXIF LensModel', 'Image YResolution', 'EXIF ComponentsConfiguration', 'Image GPSInfo', 'EXIF ISOSpeedRatings', 'EXIF ExposureMode', 'EXIF Flash', 'EXIF FlashPixVersion', 'GPS GPSLatitudeRef', 'EXIF ExposureBiasValue', 'Thumbnail JPEGInterchangeFormatLength', 'Thumbnail Compression', 'Image YCbCrPositioning', 'EXIF MakerNote', 'EXIF FNumber', 'JPEGThumbnail', 'MakerNote Tag 0x0001', 'EXIF ColorSpace', 'EXIF SubSecTimeDigitized', 'Thumbnail JPEGInterchangeFormat', 'MakerNote Tag 0x0004', 'EXIF SubjectArea', 'Image ResolutionUnit', 'EXIF SensingMethod', 'Image DateTime', 'Image Orientation', 'EXIF ExifVersion', 'Image ExifOffset', 'GPS GPSImgDirectionRef', 'MakerNote Tag 0x0014', 'Thumbnail YResolution', 'EXIF DateTimeOriginal', 'MakerNote Tag 0x0005', 'EXIF LensMake', 'EXIF DateTimeDigitized', 'MakerNote Tag 0x0003', 'GPS GPSTimeStamp', 'EXIF ExposureTime', 'GPS Tag 0x001F', 'EXIF SubSecTimeOriginal', 'GPS GPSLatitude', 'Image Software', 'EXIF ApertureValue', 'GPS GPSDate', 'EXIF ExposureProgram', 'GPS GPSSpeed', 'EXIF ExifImageLength', 'EXIF MeteringMode', 'GPS GPSLongitudeRef', 'EXIF FocalLength', 'Image XResolution'])

追踪

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-14-949ba89a1248> in <module>()
     16 #        lon = tags["GPS GPSLongitude"]
     17 #        output['lon'].append(lon)
---> 18         output['lat'].append(tags['GPS GPSLatitude'])
     19         for tag in tags.keys():
     20             if tag in ('GPS GPSLongitude','GPS GPSLatitude'):

KeyError: 'GPS GPSLatitude'

链接到照片: https://drive.google .com/a/cornell.edu/file/d/0B1DwcbbAH1yuTEs0cUhhODdlNnc/view

此照片的打印声明的输出

Output of the print statement for this photo

IMG_6680.JPG
Key: GPS GPSLongitude, value [76, 29, 353/20]
Key: GPS GPSLatitude, value [42, 26, 5069/100]

推荐答案

GPS GPSLatitudeGPS GPSLongitude可能不存在于所有标记字典中.

GPS GPSLatitude and GPS GPSLongitude may not be present in all tag dicts.

代替访问tags['GPS GPSLatitude']& tags['GPS GPSLongitude'],您还可以通过tags.get('GPS GPSLatitude')& tags.get('GPS GPSLongitude')这将返回None而不是引发错误,在这里您可以应用if-else条件来验证这些键不存在的地方.

Instead of accessing keys as tags['GPS GPSLatitude'] & tags['GPS GPSLongitude'] , you can also access these as tags.get('GPS GPSLatitude') & tags.get('GPS GPSLongitude') This wil return None instead of throwing error, where you can apply if-else condition also to verify where these keys are not present.

这篇关于键在字典中时出现键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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