字典中的值并不总是被替换



我想用新值替换dictionary中的值。然而,有时它们会被替换,有时不会…

文件可在此下载:https://easyupload.io/imkzb9

with open('zip_codes_germany.json') as originalFile:
zipCodes = json.load(originalFile)
for index, feature in enumerate(zipCodes):
if feature['place'] == 'Berlin':
zipCode = feature['zipcode']
newQuery = f"https://nominatim.openstreetmap.org/search?postalcode={zipCode}&country=Germany&format=json"
with urllib.request.urlopen(newQuery) as response:
jsonData = json.loads(response.read())
try:
feature['community'] = jsonData[0]['display_name']
zipCodes[index] = feature
except IndexError:
print(zipCode) # only done once
time.sleep(2)
with open('zip_codes_germany_2.0.json', 'w') as newFile:
newFile.write(json.dumps(zipCodes))

现在,当搜索zipcode=10997时,键community的原始值Berlin, Stadt仍然存在。搜索zipcode=10318, OSM API返回的display_name的值取代了原来的community的值。为什么呢?

原因是有些字典不符合您的更新条件。

意思是,你正在对一个字典列表执行更新。只有当字典的'place'键的值为'Berlin'时才执行更新,即:

if feature['place'] == 'Berlin':

邮编10318的字典是:

{
"country_code": "DE",
"zipcode": "10318",
"place": "Berlin",
"state": "Berlin",
"state_code": "BE",
"province": "",
"province_code": "00",
"community": "Berlin, Stadt",
"community_code": "11000",
"latitude": "52.4835",
"longitude": "13.5287"
},

键"位置"的字典值为"berlin"。所以它满足条件并得到更新。

邮编10997的字典是:

{
"country_code": "DE",
"zipcode": "10997",
"place": "Berlin Kreuzberg",
"state": "Berlin",
"state_code": "BE",
"province": "",
"province_code": "00",
"community": "Berlin, Stadt",
"community_code": "11000",
"latitude": "52.5009",
"longitude": "13.4356"
},

键'place'的值是' Berlin kreuzberg ';(即不是"柏林")。由于不符合条件,因此不更新

相关内容

  • 没有找到相关文章

最新更新