1

我有一个字符串:

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 字典。我可以使用 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用作字典,例如:datalist['smallImage']等。

4

2 回答 2

1

用','、':'分割后的每一项。像这样:

datadict = {}
for item in datalist.split(','):
    key, value = item.split(':', 1)
    datadict[key.strip()] = value.strip()
于 2013-06-18T06:56:52.330 回答
1

将 dict 理解与str.splitand一起使用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'
于 2013-06-18T07:00:44.930 回答