-2

I have about 50 urls named url1.....url50 I want to make a dictionary of these variables for example:

url1 = "https://example1.com"
url2 = "https://example2.com"
url3 = "https://example3.com"

. . I tried this::

all_urls = {}
a= 'url'

for i in range(1,51):

    all_urls[a+str(i)] = a+str(i)

For this I get the keys right but how can I get variables as the value.
Output:

{'url1': 'url1',
 'url10': 'url10',
 'url11': 'url11',
 'url12': 'url12',
 'url13': 'url13',
 'url14': 'url14',
 'url2': 'url2',
 'url3': 'url3',
 'url4': 'url4',
 'url5': 'url5',
 'url6': 'url6',
 'url7': 'url7',
 'url8': 'url8',
 'url9': 'url9'


Desired output:

'url1' : 'https://example.com'
'url2' : 'https://example.org'
'url3' : 'https://example.com'


and so on..
Rishi
  • 313
  • 1
  • 4
  • 18

2 Answers2

2

You can use globals here.

Ex:

url1 = "https://example1.com"
url2 = "https://example2.com"
url3 = "https://example3.com"

all_urls = {}
a= 'url'

for i in range(1,4):
    all_urls[a+str(i)] = globals()[a+str(i)]
print(all_urls)

Output:

{'url1': 'https://example1.com', 'url3': 'https://example3.com', 'url2': 'https://example2.com'}
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

Use locals()

>>> url1 = "https://example1.com"
>>> url2 = "https://example2.com"
>>> url3 = "https://example3.com"
>>> 
>>> {k:v for k,v in locals().items() if k.startswith('url')}
{'url3': 'https://example3.com', 'url1': 'https://example1.com', 'url2': 'https://example2.com'}
Sunitha
  • 11,777
  • 2
  • 20
  • 23