简体   繁体   中英

Convert string dict type to dict

I am trying to convert a column of the data frame to dict using python.

The dataframe is of the form

filename        bbox-coordinates

image_name1     '{""name"":""rect"",""x"":161,""y"":562,""width"":51,""height"":96}'
image_name2     '{""name"":""rect"",""x"":151,""y"":542,""width"":32,""height"":69}'
image_name3     '{""name"":""rect"",""x"":140,""y"":42,""width"":30,""height"":45}'

the bbox-coordinate value is of type string and I am trying to convert it to dict.

dataframe['bbox-coordinate'][2]
output: '{""name"":""rect"",""x"":140,""y"":42,""width"":30,""height"":45}' which is string

Here:

 [1] type(dataframe['region_shape_attributes'][0])
output: str

I tried using:

ast.literal_eval --- doesn't work 
json.loads(dataframe['bbox-coordinate'][2]) 
output: JSONDecodeError: Expecting ':' delimiter: line 1 column 4 (char 3)

My ultimate goal is to convert the entire dataframe into YOLO format.txt with image class name, this has only one class ie 0 and to extract the x, y, height and width in the YOLO.txt format for each file_name.

For some reason, it seems like your strings have double double-quotes in them ( "" ). Just replace them with single double-quotes ( " ) and ast.literal_eval() will work just fine.

from ast import literal_eval

strings = [
    '{""name"":""rect"",""x"":161,""y"":562,""width"":51,""height"":96}',
    '{""name"":""rect"",""x"":151,""y"":542,""width"":32,""height"":69}',
    '{""name"":""rect"",""x"":140,""y"":42,""width"":30,""height"":45}'
    ]

dicts = []
for s in strings:
    d = literal_eval(s.replace('""', '"'))
    dicts.append(d)

print(dicts)

returns

[{'name': 'rect', 'x': 161, 'y': 562, 'width': 51, 'height': 96}, 
 {'name': 'rect', 'x': 151, 'y': 542, 'width': 32, 'height': 69}, 
 {'name': 'rect', 'x': 140, 'y': 42, 'width': 30, 'height': 45}]

I found a solution using json

import json

strigDicts = [
    '{""name"":""rect"",""x"":161,""y"":562,""width"":51,""height"":96}',
    '{""name"":""rect"",""x"":151,""y"":542,""width"":32,""height"":69}',
    '{""name"":""rect"",""x"":140,""y"":42,""width"":30,""height"":45}'
    ]

dicts = []
for d in strigDicts:
    dicts.append(json.loads(d.replace('""', '"')))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM