Python:字典的值是字符串列表

时间:2016-09-11 12:25:28

标签: python dictionary

reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\""
print reclist
data= {
   "ids": [
      reclist #"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"
   ]
}
print data

输出:`

"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"`

{'ids': [' "MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7" ']}

但期望输出是:

"MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"
{'ids': ["MOBEEVHDBBYSQFC8","MOBE9J587QGMXBB7"]}

当我打印rectlist时,它没有显示额外的'',但当我在reclist中使用data时,由于reclist中的额外'',显示错误urllib2.HTTPError: HTTP Error 400: Bad Request,因为我必须将此数据添加到urllib2.Request。如何在数据中使用reclist时删除额外的''

2 个答案:

答案 0 :(得分:1)

reclist是一个不可迭代的字符串,您可以使用ast.literal_eval直接将其转换为元组:

In [60]: import ast

In [61]: reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\""

In [62]: ast.literal_eval(reclist)
Out[62]: ('MOBEEVHDBBYSQFC8', 'MOBE9J587QGMXBB7')

答案 1 :(得分:1)

您还可以split()strip()双引号:

>>> reclist="\"MOBEEVHDBBYSQFC8\",\"MOBE9J587QGMXBB7\""
>>> [item.strip('"') for item in reclist.split(",")]
['MOBEEVHDBBYSQFC8', 'MOBE9J587QGMXBB7']