# Showing the domain of a URL

I have such a method which takes a URL, such as http://twitter.com/ttt or twitter.com/dasd, and should show its domain with http: http://twitter.com and name twitter

def show_domain(url):
sites = {
'pininterest': ['http://www.pininterest.com/', 'pininterest']
}

else:
brand = sites['pininterest'][1]


Is there way to optimise this code?

• Have you considered using the urlparse module? – jcollado Aug 12 '14 at 11:46

You can use tuple unpacking/list unpacking to write :

if sites['twitter'][0] in url:
else:


Now, the data structure you are using is a bit akward because you don't use the key at all. Instead of mapping string to list of strings, you could have a list of list of strings. Even better, you could use list of tuple of strings :

sites = [
('http://www.pininterest.com/', 'pininterest')
]

if sites[0][0] in url:
elif sites[1][0] in url:
else:


Now, this seems to be begging to be written with a loop

for (link, brand) in sites:
return None # or anything you like

• but it local variables link, brand are unused, pycharm says – user2424174 Aug 12 '14 at 11:14
• @user2424174 then it is a bug in pycharm, because they are being returned, so used. – Davidmh Aug 12 '14 at 12:34