繁体   English   中英

如何在 python 中将字符串转换为 dict 类型

[英]How to convert string to a dict type in python

我有一个字符串,我想在 python 中转换为 dict 类型。

示例字符串:

'projectid=871106/interactionmonth=201701' 

预期 output:

{"projectid":871106,"interactionmonth":201701}
input = 'projectid=871106/interactionmonth=201701'

key = ""
value = ""
switch = False
result = {}
for character in range(len(input)):
    if input[character] == "=": switch = True
    elif input[character] == "/" or character == len(input) - 1:
        result[key] = int(value)
        switch = False
        key = ""
        value = ""
    else:
        if (switch): value += input[character]
        else : key += input[character]
print(result)


输出:

{'projectid': 871106, 'interactionmonth': 20170}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM