Python解析字符串值并加载到字典中

RaA*_*aAm 1 python python-2.7 python-3.x

我需要解析一个字符串值并加载到 python 字典中

输入:

attributes = "LIFETIME=203421,ID=acr44,SCOPE=[open,basic.operation:read,common.operation:write],USER=b611-410e,CLAIMS_"
Run Code Online (Sandbox Code Playgroud)

预期输出:

attributesDictionary = { "LIFETIME" : "203421",
                         "ID" : "acr44",
                         "SCOPE" : "[open,basic.operation:read,common.operation:write]",
                         "USER" : "b611-410e",
                         "CLAIMS_" : None
                         }

attributesDictionary["ID"]
>>> 'acr44'

attributesDictionary["SCOPE"]
>>> '[open,basic.operation:read,common.operation:write]'
Run Code Online (Sandbox Code Playgroud)

我是 python 编程的新手。我们怎样才能做到这一点?

Chr*_*ris 6

一种使用方式re.split

import re

d = {}
for k in re.split(",(?![^\[]*\])", attributes):
    key, *val = k.split("=", 1) 
    d[key] = val[0] if val else None
d
Run Code Online (Sandbox Code Playgroud)

输出:

{'CLAIMS_': None,
 'ID': 'acr44',
 'LIFETIME': '203421',
 'SCOPE': '[open,basic.operation:read,common.operation:write]',
 'USER': 'b611-410e'}
Run Code Online (Sandbox Code Playgroud)