Python如何将字符串拆分为字典

很少有Python示例向您展示如何将字符串拆分为字典。

1.1 将字符串拆分成字典

#!/usr/bin/python
 
str = "key1=value1;key2=value2;key3=value3"
 
d = dict(x.split("=") for x in str.split(";"))
 
for k, v in d.items():
    print(k, v)

输出量

key1 value1
key2 value2
key3 value3

1.2 将两个列表转换成字典

#!/usr/bin/python
 
str1 = "key1 | key2 | key3"
str2 = "value1 | value2 | value3"
 
keys = str1.split("|")
values = str2.split("|")
 
d = {}
 
for k in keys:
    k = k.strip() # key trim
    for v in values:
        d[k] = v.strip() # value trim
 
for k, v in d.items():
    print(k, v)

输出量

key1 value1
key2 value2
key3 value3

1.3  zip示例

#!/usr/bin/python
str1 = "key1 | key2 | key3"
str2 = "value1 | value2 | value3"
 
keys = str1.split(" | ")
values = str2.split(" | ")
 
d = dict(zip(keys, values))
 
for k, v in d.items():
    print(k, v)

输出量

key1 value1
key2 value2
key3 value3