>>> import urllib >>> urllib.urlencode({'p': [1, 2, 3]}, doseq=True) 'p=1&p=2&p=3'
Here is what the above code is Doing:
1. urllib.urlencode() takes a dictionary and returns a string.
2. The dictionary we’re passing it has a single key, ‘p’, whose value is a list.
3. The doseq parameter tells urllib.urlencode() to treat the list as a sequence,
and encode each element of the list as a separate parameter.
If you don’t pass doseq=True, urllib.urlencode() will encode the list as a single
parameter, and you’ll end up with a string that looks like this:
>>> urllib.urlencode({‘p’: [1, 2, 3]})
‘p=%5B1%2C+2%2C+3%5D’
The %5B and %5D are URL-encoded brackets, and the %2C is an encoded comma.
If you want to encode a single value, you can pass it as a list:
>>> urllib.urlencode({‘p’: 1})
‘p=1’
If you want to encode multiple values with the same key, you can pass a list of
values:
>>> urllib.urlencode({‘p’: [1, 2, 3]})
‘p=1&p=2&p=3’
If you want to encode multiple values with different keys, you can pass a
dictionary of lists:
>>> urllib.urlencode({‘p’: [1, 2, 3], ‘q’: [‘a’, ‘b’, ‘c’]})
‘p=1&p=2&p=3&q=a&q=b&q=c’
If you want to encode multiple values with the same key, you can pass a list of
values:
>>> urllib.urlencode({‘p’: [1, 2, 3]})
‘p=1&p=2&p=3’
If you want to encode multiple values with different keys, you can pass a
dictionary of lists:
>>> urllib.urlencode({‘p’: [1, 2, 3], ‘q’: [‘a’, ‘b’, ‘c’]})
‘p=1&p=2