I've to load an excel file including a dict like string without text qualifier (""
) in a column which looks like this:
{Item: 0815, sequence: 1, qty: 3, name: some name, comapny: some company},
{Item: 4711, sequence: 2, qty: 4, name: some name, company: some company}
I've tried to create the dict using the following statement:
item_string = dict(item_string)
but I receive the following error message
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Any ideas how to create the dict based on this string?
CodePudding user response:
If each line is a dictionary, you can parse it as YAML:
import yaml
s = """{Item: 0815, sequence: 1, qty: 3, name: some name, company: some company},
{Item: 4711, sequence: 2, qty: 4, name: some name, company: some company}"""
for line in s.splitlines():
# remove white-space and comma
clean = line.strip().strip(",")
# load dictionary using yaml
d = yaml.load(clean, Loader=yaml.FullLoader)
print(d)
Output
{'Item': '0815', 'sequence': 1, 'qty': 3, 'name': 'some name', 'company': 'some company'}
{'Item': 4711, 'sequence': 2, 'qty': 4, 'name': 'some name', 'company': 'some company'}
CodePudding user response:
For a solution in pure python, you can consider something like this:
s = "{Item: 4711, sequence: 2, qty: 4, name: some name, company: some company}"
# split the elements and organize them in a tuple:
l = [(i.split(":")[0], i.split(":")[1]) for i in s[1:-1].split(",")]
# take that tuple and generate a dictionary using dictionary comprehension:
d = {k:v for k,v in l}
This shall give you something like this:
{'Item': ' 4711',
' sequence': ' 2',
' qty': ' 4',
' name': ' some name',
' company': ' some company'}
some additional formatting may be needed.