im given the following input:
'family': 'man: name, woman: name, child: name , grandma: name, grandpa: name'
where 'family' is a key, and its value is a bunch of other key-value pairs. as you can tell, you cant parse it using json() because this string is not structured in json format. ive been trying for hours to parse this string into a dictionary/json valid string so i could work with it properly and change name values accordingly. would appreciate the help.
CodePudding user response:
Assuming that no key and no value ever contains a comma or a colon, you could do this:
def split_to_dict(string: str) -> dict[str, str]:
output = {}
for pair in string.split(','):
key, value = pair.split(':')
output[key.strip()] = value.strip()
return output
Calling it like this:
s = 'man: name, woman: name, child: name , grandma: name, grandpa: name'
d = split_to_dict(s)
print(d)
gives the following:
{'man': 'name', 'woman': 'name', 'child': 'name', 'grandma': 'name', 'grandpa': 'name'}
For readability purposes, I would refrain from doing this in a dictionary comprehension.
CodePudding user response:
You first need to convert it to a correct json.
d = {'family': 'man: name, woman: name, child: name , grandma: name, grandpa: name'}
d['family'] = re.sub("(\w )", r'"\1"', d['family'])
# now parse it
json.loads("{" d['family'] "}")
CodePudding user response:
Assuming the input is loaded in as a dictionary and we want to turn the value of family
into a corresponding dictionary of key-value pairs. We can do that by doing some string processing as such:
>>> d = {'family': 'man: name, woman: name, child: name , grandma: name, grandpa: name'}
>>> d['family'] = { x.split(':')[0] : x.split(':')[1].strip() for x in d['family'].split(', ')}
>>>
>>> d['family']
>>> {'man': 'name','woman': 'name', 'child': 'name', 'grandma': 'name', 'grandpa': 'name'}
We first split the value of family
into key-value strings, and then we further split each key-value string to turn it into the corresponding key-value pair in the list comprehension of the new dictionary.