1

I need to parse a string value and load into a python dictionary

Input:

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

Expected Output :

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]'

I am new to python programming. How can we achieve this ?

5
  • 1
    What have you tried so far? Commented Jul 6, 2020 at 10:12
  • Tried using python regex to identify a key value pair separated by '=' . But it is not working for all scenarios Commented Jul 6, 2020 at 10:14
  • Could you show the exact code you tried, and an example scenario where it doesn't work? Commented Jul 6, 2020 at 10:18
  • If you create the source line, save it to json and then read from json. Commented Jul 6, 2020 at 10:19
  • @Evg I am not creating the source line, it is coming as a string value from a gateway. Commented Jul 6, 2020 at 10:21

2 Answers 2

6

One way using 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

Output:

{'CLAIMS_': None,
 'ID': 'acr44',
 'LIFETIME': '203421',
 'SCOPE': '[open,basic.operation:read,common.operation:write]',
 'USER': 'b611-410e'}
Sign up to request clarification or add additional context in comments.

2 Comments

can you please explain me this regex (?![^[]*])
@RaAm. It is looking for , to split but not if (i.e. negative lookahead (?!) it is inside a part that starts with [, and anything (*) until ].
0

Not sure but here I observed a pattern that all the keys are in capital letter. If that is the case, You can do the following,

import re

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

keys = re.findall("[A-Z]+", attributes)
values = re.findall("[^A-Z=]+,", attributes)
attributesDictionary = dict(zip(keys,values))

this will give you the following output,

{'LIFETIME': '203421',
 'ID': 'acr44',
 'SCOPE': '[open,basic.operation:read,common.operation:write]',
 'USER': 'b611-410e',
 'CLAIMS': '_'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.