I encountered a string input in the following format:
'1:[2,3],4:[1],3:[4],2:[4]'
How to transform it into the following format:
{1:[2,3],4:[1],3:[4],2:[4]}
Thanks!
I encountered a string input in the following format:
'1:[2,3],4:[1],3:[4],2:[4]'
How to transform it into the following format:
{1:[2,3],4:[1],3:[4],2:[4]}
Thanks!
from ast import literal_eval
d = literal_eval('{1:[2,3],4:[1],3:[4],2:[4]}')
print(d)
Output:
{1: [2, 3], 4: [1], 3: [4], 2: [4]}
Some fun with regex :)
import re
parse_re = r"(\d+):\[([^\]]*)\]"
raw_str = '1:[2,3],4:[1],3:[4],2:[4]'
res_dict = {}
for curr_match in re.finditer(parse_re, raw_str):
dict_key, dict_val_str = curr_match.groups()
dict_key = int(dict_key)
dict_val = [int(item) for item in dict_val_str.split(',')]
res_dict[dict_key] = dict_val
I'd like to dedicate this hardcore fun method to Derek Eden.
import re
parse_re = r"(\d+):\[([^\]]*)\]"
raw_str = '1:[2,3],4:[1],3:[4],2:[4]'
match_groups = (curr_match.groups() for curr_match in re.finditer(parse_re, raw_str))
res_dict = {int(curr_key): [int(item) for item in curr_val.split(',')] for curr_key, curr_val in match_groups}