How should i convert this string into dict in python?

Question:

Is there any way to convert this string into list of item???

'variants': ['{{attribute: 3, value: Red}, {attribute: 4, value: Yellow}}']
Asked By: unknown

||

Answers:

str_list = "'variants': ['{{attribute: 3, value: Red}, {attribute: 4, value: Yellow}, {attribute: 5, value: Green}}','{{attribute: 6, value: Red0}, {attribute: 7, value: Yellow0}, {attribute: 8, value: Green0}}']"

l= str_list.split("'variants':")[1][2:-1].split(",")
c=0
lst=[]
for s in l:
    kv=s.split(':')[1].strip("}'").strip()
    if(c%2==0):
        key=kv
    else:
        val=kv
        lst.append({'attribute':int(key),'value':val})
    c+=1
        
print(lst)

check whether this is what you want. Results are as follows:

[{'attribute': 3, 'value': 'Red'}, {'attribute': 4, 'value': 'Yellow'}, {'attribute': 5, 'value': 'Green'}]
Answered By: YJR
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.