python将键值对参数转换成字典

def strToDict(string):
    strList = []    # 创建空列表
    for i in string.split("&"):     # 循环遍历第一次切割结果
        strList.append(i.split("=", 1))     # 切割第二次写入列表中,只切割一次防止把值里的=切割掉
    return dict(strList)    # 列表转换为字典


print(strToDict("id=4&name=zengyu&age=33"))

运行结果:

{'id': '4', 'name': 'zengyu', 'age': '33'}

注意:dict将列表转换为字典,列表要是二维列表,且元素长度必须为2;

我们可以把上述代码复杂化,打印每次切割结果,更能懂得是如何转换为字典的:

string = "id=4&name=zengyu&age=1815=33"
strList = []  # 创建空列表
first = string.split("&")
print(first)  # 查看第一次切割结果
for i in first:
    second = i.split("=", 1)
    print(second)   # 获取到二次切割长度为2的列表
    strList.append(second)  # 将二次切割的列表添加到空列表中
print(strList)  # 打印二维列表
newDict = dict(strList)     # 转化为字典
print(newDict)  

运行结果:

['id=4', 'name=zengyu', 'age=1815=33']
['id', '4']
['name', 'zengyu']
['age', '1815=33']
[['id', '4'], ['name', 'zengyu'], ['age', '1815=33']]
{'id': '4', 'name': 'zengyu', 'age': '1815=33'}

上述方法是通过定义空列表,然后使用dict函数转化

另一种方法是通过定义空字典,与上一方法大同小异:

def strToDict(string):
    newDict = {}
    for item in string.split("&"):
        strList = item.split("=", 1)
        newDict[strList[0]] = strList[1]    # 设置空字典的key等于切割列表的第一个元素,value等于第二个元素
    return newDict


print(strToDict("id=4&name=zengyu&age=1815=33"))

 

posted @ 2021-12-29 23:04  童薰  阅读(816)  评论(1编辑  收藏  举报