4

Let's say I have this code:

>>> import urlparse
>>> url = "http://google.com"
>>> s = urlparse.urlsplit(url)
>>> print s
SplitResult(scheme='http', netloc='google.com', path='', query='', fragment='')
>>> print 'scheme ',s.scheme    
scheme  http
>>> print 'netloc ',s.netloc
netloc  google.com

As you can see, I can iterate over the items manually, but how can I do this automatically? I want to do something like this:

# This doesn't work:
for k,v in s.items():
    print '%s : %s'%(k,v)

2 Answers 2

7

You could use the internal _asdict method:

>>> import urlparse
>>> url = "http://google.com"
>>> s = urlparse.urlsplit(url)
>>> s
SplitResult(scheme='http', netloc='google.com', path='', query='', fragment='')
>>> s._asdict()
OrderedDict([('scheme', 'http'), ('netloc', 'google.com'), ('path', ''), ('query', ''), ('fragment', '')])
>>> d = s._asdict()
>>> for k,v in d.items():
...     print k, repr(v)
... 
scheme 'http'
netloc 'google.com'
path ''
query ''
fragment ''

To clarify a point raised in the comments, despite the prefix _, which usually indicates a method not part of a public interface, the method is a public one. It's given the prefix to avoid name conflicts, as the namedtuple docs explain [link]:

To prevent conflicts with field names, the method and attribute names start with an underscore.

And in Python 3, this is much easier due to an implementation change:

>>> vars(urllib.parse.urlsplit("http://www.google.ca"))
OrderedDict([('scheme', 'http'), ('netloc', 'www.google.ca'), ('path', ''), ('query', ''), ('fragment', '')])
Sign up to request clarification or add additional context in comments.

6 Comments

Is the _asdict() method documented anywhere? I didn't see it.
I found it by looking at help(s), where s is the SplitResult object.
@DSM Ahh, okay. I wasn't aware that SplitResult was a namedtuple. The documentation I was reading about urlparse just said it was a tuple.
Note that methods with a leading underscore are meant to be internal and are not considered part of the public interface. Use them carefully and expect them to change in the future.
|
1
>>> url = "http://google.com"
>>> s = urlparse.urlsplit(url)
>>> scheme, netloc, path, query, fragment = s
>>> scheme
'http'
>>> netloc
'google.com'
>>> path
''
>>> query
''
>>> fragment
''

As shown above the SplitResult is really a fancy tuple so you can use standard assignment as well.

>>> scheme, netloc, _, _, _ = s # I only want the scheme and netloc

Enjoy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.