将字符串"k:1|k1:2|k2:3|k3:4"处理成python字典

#第一种方法

s1 = “k:1|k1:2|k2:3|k3:4”
d = {}

print(s1)

s2 = s1.split(’|’)
print(s2)
for n in s2:
n1 = n.split("?
d[str(n1[0])] = n1[1]
print(d)

#第二种方法
s1 = “k:1|k1:2|k2:3|k3:4”
d = {}

print(s1)

s2 = s1.split(’|’)
print(s2)
for n in s2:
n1 = n.split("?
d.setdefault(n1[0], n1[1])
print(d)

#第三种方法;
s1 = “k:1|k1:2|k2:3|k3:4”
d = {}

print(s1)

s2 = s1.split(’|’)
print(s2)
for n in s2:
n1 = n.split("?
d[n1[0]] = n1[1]
print(d)

4/
d = {}
items = s.split(’|’)
for x in items:
k, v = x.split(’:’)
d[k] = int(v)

print(d)

5
a = “k:1|k1:2|k2:3|k3:4”
print dict([m.split(’:’) for m in a.split("|")])

你可能感兴趣的:(py)