将字符串 “k:1|k1:2|k2:3|k3:4” 转换成字典{“k”:1,”k1”:2,”k2”:3,”k3”:4}

将字符串 “k:1|k1:2|k2:3|k3:4” 转换成字典{“k”:1,”k1”:2,”k2”:3,”k3”:4},请写出代码:

法一:

str = "k:1|k1:2|k2:3|k3:4"
li=str.split("|")
d=dict()
for i in li:
    key=i.split(":")[0]
    value=eval(i.split(":")[1])
    d[key]=value
print(d)

法二:字典推导式:

d = {k:int(v) for t in str.split("|") for k, v in (t.split(":"), )}
print(d)

 

你可能感兴趣的:(python题目)