Reputation: 497
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.
Upvotes: 0
Views: 45
Reputation: 353
How is this
for k1, v1 in provinceDictionary.items():
for k2,v2 in v1.items():
targetUrl = baseURL+'/'.join((k1,k2,v2))+'.html'
Upvotes: 1
Reputation: 54733
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" )
Upvotes: 1
Reputation: 10809
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
>>>
Upvotes: 3