[SOLVED] How should i convert this string into dict in python?

Issue

This Content is from Stack Overflow. Question asked by unknown

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

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



Solution

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'}]


This Question was asked in StackOverflow by unknown and Answered by YJR It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?