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)
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', '')])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With