很少有Python示例向您展示如何将字符串拆分为字典。
1、将字符串拆分成字典#!/usr/bin/pythonstr = "key1=value1;key2=value2;key3=value3"d = dict(i.split("=") for i in str.split(";"))print(d)for k, v in d.items():print(k, v)结果:
image.png2、将两个列表转换成字典①方法一 enumerate()str1 = "key1 | key2 | key3"str2 = "value1 | value2 | value3"li1 = str1.split("|")li2 = str2.split("|")dic = {}for i, v in enumerate(li1):dic[v] = li2[i]print(dic)for k, v in dic.items():print(k, v)结果:
image.png②方法二 zip()str1 = "key1 | key2 | key3"str2 = "value1 | value2 | value3"li1 = str1.split("|")li2 = str2.split("|")d = dict(zip(li1, li2))print(d)for k, v in d.items():print(k, v)结果:
image.png希望