KeyError:'其他'没有名称'其他'在python字典中

时间:2015-12-29 10:51:22

标签: python dictionary

我正在尝试编写一个python脚本来合并下面显示的两个csv文件,变量' countries'是一个大约9个国家的字典,数据结构是这样的:

{'FR': {'country_destination': 'FR', 'destination_language ': 'fra', 'lng_destination': '2.209667', 'language_levenshtein_distance': '92.06', 'destination_km2': '643801.0', 'distance_km': '7682.945', 'lat_destination': '46.232193'}, 'NL': {'country_destination': 'NL', 'destination_language ': 'nld', 'lng_destination': '5.29525', 'language_levenshtein_distance': '63.22', 'destination_km2': '41543.0', 'distance_km': '7524.3203', 'lat_destination': '52.133057'}

现在这部分代码:

else:
            correctedRow['destination_language'] = countries[country].get('destination_language', 'NDF') 
            correctedRow['lng_destination'] = countries[country].get('lng_destination', 'NDF')
            correctedRow['language_levanshtien_distance'] = countries[country].get('language_levanshtien_distance', 'NDF')
            correctedRow['destination_km2'] = countries[country].get('destination_km2', 'NDF')

给了我以下错误:

KeyError                                  Traceback (most recent call last)
<ipython-input-9-f3b0363bcc74> in <module>()
     26                 correctedRow['lat_destination'] = 'NDF'
     27             else:
---> 28                 correctedRow['destination_language'] = countries[country].get('destination_language', 'NDF')
     29                 correctedRow['lng_destination'] = countries[country].get('lng_destination', 'NDF')
     30                 correctedRow['language_levanshtien_distance'] = countries[country].get('language_levanshtien_distance', 'NDF')

KeyError: 'other'

通常,当我在python词典中尝试访问的键值丢失时会发生键错误,这就是我在代码中使用.get(keyvalue,default)的原因。但我不明白这里发生了什么。谁能解释一下?我该如何纠正这个?

1 个答案:

答案 0 :(得分:1)

最有可能的错误是查找countries[country],而不是后续get来电。心理调试说country"other",并且它在countries中找不到该密钥。

你的评论要求&#34;我使用.get(密钥,默认)的原因是当密钥不存在时返回默认值?&#34;对此,答案是,不,您正在进行两阶段查找,首先是dict dict个,而第二个是dict返回的结果第一阶段。 .get可以帮助您避免在查找的第二阶段失败,但如果您不在第一阶段使用它,那么它无法在第一阶段将您从失败中拯救出来。

如果目标是对某个国家/地区进行自动生存,则可以将countries[country]更改为countries.get(country, {}),以便在两个阶段都使用.get,不存在的国家/地区的效果是获取默认值。或者您可以使用countries.setdefault(country, {}),其行为类似于get,但它会将密钥设置为默认值,然后在密钥不存在时将其返回。

为了提高性能(避免冗余查找和冗余默认dict构造),您可以将代码块更改为:

country_data = countries.get(country, {})
correctedRow['destination_language'] = country_data.get('destination_language', 'NDF') 
correctedRow['lng_destination'] = country_data.get('lng_destination', 'NDF')
correctedRow['language_levanshtien_distance'] = country_data.get('language_levanshtien_distance', 'NDF')
correctedRow['destination_km2'] = country_data.get('destination_km2', 'NDF')
相关问题