Home > Mobile >  How should i convert this string into dict in python?
How should i convert this string into dict in python?

Time:09-19

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

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

CodePudding user response:

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