简体   繁体   中英

How could I iterate through a url using a nested dictionary?

I have the following url structure

https://www.website.com/business/[provinceCode]/[city]/[city code].html

and have the following dictionary structure:

dictionary = {
   provinceCode1: {
       city1: city code 1
   },
   provinceCode2: {
       city2: city code 2
   }
}

I would like to iterate through the key, value pairs in order to print a list. My code as follows:


baseURL = 'https://www.website.com/business/'

provinceDictionary = {
    'AB': {
        'calgary': '91',
        'edmonton': '183',
        'canmore': '96'
        },
    
    'BC': {
        'vancouver': '961',
        'surrey': '934',
        'victoria': '966'
    }
}

Now this is the part I am unsure, how I can access the following nested parts of the dictionary:

for key, value in provinceDictionary:
    page  = str(baseURL) + '/' + (key1-province code-AB) + "/" + (Subkey1-city-calgary) + "/" + (subvalue1-city code-91) + '.html'
    print(page)

My expected output would be 'https://www.website.com/business/AB/calgary/91.html'

Any help is greatly appreciated.

baseURL = 'https://www.website.com/business/{}/{}/{}.html'

provinceDictionary = {
    'AB': {
        'calgary': '91',
        'edmonton': '183',
        'canmore': '96'
        },
    
    'BC': {
        'vancouver': '961',
        'surrey': '934',
        'victoria': '966'
    }
}

for province, dct in provinceDictionary.items():
    for city, code in dct.items():
        print(baseURL.format(province, city, code))

Output:

https://www.website.com/business/AB/calgary/91.html
https://www.website.com/business/AB/edmonton/183.html
https://www.website.com/business/AB/canmore/96.html
https://www.website.com/business/BC/vancouver/961.html
https://www.website.com/business/BC/surrey/934.html
https://www.website.com/business/BC/victoria/966.html
>>> 

baseURL is already a string. You don't need to convert it.

for key, value in provinceDictionary.items():
    for subkey, subval in key.items():
        print( f"{baseURL}/{key}/{subkey)/(subval).html" )

How is this

for k1, v1 in provinceDictionary.items():
    for k2,v2 in v1.items():
        targetUrl = baseURL+'/'.join((k1,k2,v2))+'.html'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM