我有一个字符串:
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'"
我想将此字符串转换为Python Dict。我可以使用split来打破字符串和表单列表:
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'"]
等等,以获得理想的结果......
我有任何简单的方法可以将此datalist
用作dict:datalist['smallImage']
等。
答案 0 :(得分:1)
拆分后按','拆分每个项目。像这样:
datadict = {}
for item in datalist.split(','):
key, value = item.split(':', 1)
datadict[key.strip()] = value.strip()
答案 1 :(得分:1)
对str.split
和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'