parse query string with urllib in Python 2.4

后端 未结 3 489
轻奢々
轻奢々 2021-02-05 21:16

Using Python2.4.5 (don\'t ask!) I want to parse a query string and get a dict in return. Do I have to do it \"manually\" like follows?

>>> qs = \'first=         


        
相关标签:
3条回答
  • 2021-02-05 21:41

    You have two options:

    >>> cgi.parse_qs(qs)
    {'second': ['4'], 'third': ['3'], 'first': ['1']}
    

    or

    >>> cgi.parse_qsl(qs)
    [('first', '1'), ('second', '4'), ('third', '3')]
    

    The values in the dict returned by cgi.parse_qs() are lists rather than strings, in order to handle the case when the same parameter is specified several times:

    >>> qs = 'tags=python&tags=programming'
    >>> cgi.parse_qs(qs)
    {'tags': ['python', 'programming']}
    
    0 讨论(0)
  • 2021-02-05 21:57
    import urlparse
    qs = 'first=1&second=4&third=3&first=0'
    
    print dict(urlparse.parse_qsl(qs))
    
    OR
    
    print urlparse.parse_qs(qs)
    
    0 讨论(0)
  • 2021-02-05 22:03

    this solves the annoyance:

    d = dict(urlparse.parse_qsl( qs ) )
    

    personally i would expect there two be a built in wrapper in urlparse. in most cases i wouldn't mind to discards the redundant parameter if such exist

    0 讨论(0)
提交回复
热议问题