将字符串 "k:1 | k1:2 | k2:3 | k3:4",转化为字典:{k:1, k2:2 .....}

 字符串 "k:1 | k1:2 | k2:3 | k3:4",转化为字典:{k:1, k2:2, .....}

方法一:

str = "k:1 | k1:2 | k2:3 | k3:4"
def Dicts(str):
    dict = {}
    for iterms in str.split('|'):

        key, value = iterms.split(':')
        dict[key] = int(value)

    return dict

方法二: 字典推到式


dict = {k: int(v) for s in str.split('|')for k, v in (s.split(':'), )}
print(dict)

 

你可能感兴趣的:(Python习题)