I have a variable called "dict_str" that looks like this : "a = 15, a2 = 19"
(it continue for thousands of inputs).
If I try to use the dict()
function :
dict(dict_str)
it gives me this error :
ValueError: dictionary update sequence element #0 has length 1; 2 is required
But if I do this :
dict(a = 15, a2 = 19)
it works fine.
So I am wondering if there's a way to make it works with the dict_str
variable
This is a work around.
items = [item.split('=') for item in dict_str.split(', ')]
my_dict = {}
for key, value in items:
my_dict[key.strip()] = int(value.strip())
print(my_dict)
If you prefer a dict comprehension you can use the bellow approach
items = [item.split('=') for item in dict_str.split(', ')]
my_dict = {key.strip(): int(value.strip()) for key, value in items}
print(my_dict)
{'a': 15, 'a2': 19}
You could even use regex depending on your use case.
Example:
import re
regex = re.compile(r'(\w+) *= *(\d+)')
items = regex.findall(dict_str)
my_dict = {key: int(value) for key, value in items}
print(my_dict)
This regex should produce same output.