0%

使用Python将字典转换为query string

将字典转变为字符串 dict to string

Python3.x

1
2
3
4
5
6
# urllib.parse.urlencode(query, doseq=False, [...])
# Convert a mapping object or a sequence of two-element tuples, which may contain str or bytes objects, to a percent-encoded ASCII text string.
# Example
from urllib.parse import urlencode
urlencode({'pram1': 'foo', 'param2': 'bar'})
# pram1=foo&param2=bar

Python2.x

1
2
3
4
from urllib import urlencode

data = {'name': 'Desmond Lua', 'age': 40}
query_string = urlencode(data)

Python2 和Python3的兼容写法

1
2
3
4
5
6
try:
#python2
from urllib import urlencode
except ImportError:
#python3
from urllib.parse import urlencode

将字符串转换为字典 string to dict

Python3

方法1 使用urllib.parse.parse_qs()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# import module
import urllib.parse

# initializing string
test_str = 'gfg=4&is=5&best=yes'

# printing original string
print("The original string is : " + str(test_str))

# parse_qs gets the Dictionary and value list
res = urllib.parse.parse_qs(test_str)

# printing result
print("The parsed URL Params : " + str(res))

# The parsed URL Params : {'gfg': ['4'], 'is': ['5'], 'best': ['yes']}

方法2 使用正则表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import re

# initializing string
test_str = 'gfg=4&is=5&best=yes'

# printing original string
print("The original string is : " + str(test_str))

# getting all params
params = re.findall(r'([^=&]+)=([^=&]+)', test_str)

# assigning keys with values
res = dict()
for key, val in params:

res.setdefault(key, []).append(val)

# printing result
print("The parsed URL Params : " + str(res))

方法3 使用Split()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#python program to convert
#URL parameters to dictionary items
# initializing string
test_str = 'gfg=4&is=5&best=yes'

# printing original string
print("The original string is : " + str(test_str))

# getting all params
res = dict()
x=test_str.split("&")
for i in x:
a,b=i.split("=")
# assigning keys with values
res[a]=[b]
# printing result
print("The parsed URL Params : " + str(res))

#The original string is : gfg=4&is=5&best=yes
# The parsed URL Params : {'gfg': ['4'], 'is': ['5'], 'best': ['yes']}