Search code examples
python-3.xdictionarystring.format

How to use .format(**dict) with a dictionary that gets updated in a loop?


I am trying to do some map scraping and I fill the URL string with a parameter dictionary 'on the fly' like this:

par = {'zoom': 13, 'latmin': 2835, 'latmax': 2844, 'lonmin': 4464, 'lonmax': 4475, 'ext': 'png'}
url = 'https://some.url.com/{zoom}/{lat}/{lon}.{ext}'

for lat in range(par['latmin'], par['latmax']):
    par['lat'] = lat
    for lon in range(par['lonmin'], par['lonmax']):
        par['lon'] = lon
        url = url.format(**par)

The dictionary gets updated but for some reason the URL string is stuck at the first iteration. Why?


Solution

  • You overwrote your format string (which contains placeholders for new values) with a formatted string (where the placeholders have been replaced with the data they were holding a place for). From the second iteration onwards, there is no {lat} or {lon} placeholder in the string. If you printed url immediately after the first inner loop ran, you'd see the contents were now:

    url = 'https://some.url.com/{zoom}/2835/4464.{ext}'
    

    which still has placeholders for {zoom} and {ext}, but has fixed values for the other placeholders, so there is nothing to update on future loops.

    If you don't want that to happen, don't assign back to url after formatting, use a different name for the partially formatted string (or use a list of such partially formatted strings if you want one for every combination of lat and lon).