four-eyes
four-eyes

Reputation: 12394

Value in Dictionary is not always replaced

I want to replace values in a dictionary with new values. However, sometimes they get replaced and sometimes not...

The file can be downloaded here: 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))

Now, when searching for the zipcode=10997, the original value Berlin, Stadt for the key community is still there. Searching for the zipcode=10318, the value that the OSM API returns in display_name replaced the old community value. Why is that?

Upvotes: 1

Views: 73

Answers (1)

DarrylG
DarrylG

Reputation: 17156

The reason is some of the dictionaries don't meet your condition for updating.

Meaning, you are performing updates on a list of dictionaries. The update is only performed when the value for the 'place' key of the dictionary is 'Berlin', i.e.:

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

The dictionary with zipcode 10318 is:

{
    "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"
},

This dictionary value for key "place' is "Berlin" so it meets the condtion and gets updated.

The dictionary with zipcode 10997 is:

{
    "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"
},

This value for the key 'place' is "Berlin Kreuzberg" (i.e. not "Berlin"). Since this does not match the condition it is not updated.

Upvotes: 1

Related Questions