字典键不存在 - 但它确实存在

时间:2018-05-10 19:55:11

标签: python python-3.x dictionary

我正在使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="my-form" action="maps.html"> <input type="text" name="username" id="username" required /> <input type="submit" value="submit" /> </form>从照片中获取一些Exif信息。

目前,我正在尝试获取GPS纬度和经度,我可以这样做:

exifread

这打印出我期望的内容,它们的关键名称和值:

   GPS GPSLatitude ::: [32,52,66443/1250]
GPS GPSLatitude ::: [32,52,   531699/10000]
GPS GPSLatitude ::: [32,52,531699 / 10000]
GPS   GPSLatitude ::: [32,52,132789 / 2500]
GPS GPSLatitude ::: [32,52,   5000分之265817]

但是,为了跳过这个循环并快速获得键/值对,我尝试了(这取代了def main(): images = image_paths(IMAGE_FOLDER) # folder is say "Sample Photos\\" info = {} for img in images: _lat, _lon = "", "" tags = exifread.process_file(open(img,'rb')) for i in tags.keys(): if i == "GPS GPSLatitude": print(i, ":::", tags[i]) 循环)

for i ...

但是我收到了一个错误:

  

KeyError:&#39; GPS GPSLatitude&#39;

如何访问&#34; GPS GPSLatitude&#34; (和#34; GPS GPSLongitude&#34;)没有循环_lon = tags["GPS GPSLatitude"] 的键?

编辑:

tagstags

2 个答案:

答案 0 :(得分:3)

某些标签是否可能没有密钥'GPS GPSLatitude'

也许你可以试试

_lat = tags.get('GPS GPSLatitude', '')

这样,_lat将被设置为纬度值(如果存在),否则将设置为空字符串。

答案 1 :(得分:0)

如果任何图像没有该标记,则需要处理该异常以防止崩溃。例如:

def main():
    images = image_paths(IMAGE_FOLDER) # folder is say "Sample Photos\\"
    info = {}
    for img in images:
        _lat, _lon = "", ""
        tags = exifread.process_file(open(img,'rb'))       

        try:
            _lon = tags["GPS GPSLongitude"]
            # _lat = tags["GPS GPSLatitude"]  # presumably you also want this
            # do something with these... perhaps add to info
        except KeyError:
            pass  # move on