简体   繁体   中英

How to convert string to dict

I have a string :

datalist = "popupWin:'http://www.adachikan.net/index.php/catalog/product/gallery/id/3049/image/1861/', useZoom: 'cloudZoom', smallImage: 'http://www.adachikan.net/media/catalog/product/cache/1/image/315x400/9df78eab33525d08d6e5fb8d27136e95/1/8/187267-875-40.jpg'"

And i want to convert this string into Python Dict. I can use split to break the string and form list:

datalist.split(',') = ["popupWin:'http://www.adachikan.net/index.php/catalog/product/gallery/id/3049/image/1861/'",
 " useZoom: 'cloudZoom'",
 " smallImage: 'http://www.adachikan.net/media/catalog/product/cache/1/image/315x400/9df78eab33525d08d6e5fb8d27136e95/1/8/187267-875-40.jpg'"]

And so on to get the desired result...

I there any easy way to use this datalist as a dict like : datalist['smallImage'] etc..

Split each item after splitting by ',', by ':'. like so:

datadict = {}
for item in datalist.split(','):
    key, value = item.split(':', 1)
    datadict[key.strip()] = value.strip()

Use a dict comprehension with str.split and str.strip :

>>> dic = {k.strip(): v.strip().strip("'")  
                     for k,v in (x.split(':',1) for x in datalist.split(','))}
>>> dic
{'useZoom': 'cloudZoom', 'popupWin': 'http://www.adachikan.net/index.php/catalog/product/gallery/id/3049/image/1861/', 'smallImage': 'http://www.adachikan.net/media/catalog/product/cache/1/image/315x400/9df78eab33525d08d6e5fb8d27136e95/1/8/187267-875-40.jpg'}
>>> dic['smallImage']
'http://www.adachikan.net/media/catalog/product/cache/1/image/315x400/9df78eab33525d08d6e5fb8d27136e95/1/8/187267-875-40.jpg'

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