我有一个变量foo = "'totalteams': 10, 'totalrounds': 11"
通过字符串创建字典
为什么我不能这样做?
data=dict(foo)
所以我可以做
print data['totalteams']
我需要使用,因为谷歌的Python 2.5的。我如何做我想做的事?
感谢
我有一个变量foo = "'totalteams': 10, 'totalrounds': 11"
通过字符串创建字典
为什么我不能这样做?
data=dict(foo)
所以我可以做
print data['totalteams']
我需要使用,因为谷歌的Python 2.5的。我如何做我想做的事?
感谢
foo = "'totalteams': 10, 'totalrounds': 11"
data = eval("{%s}" % foo)
print data['totalteams']
'ast.literal_eval' 会更好。 – SingleNegationElimination
已在Python 2.6中添加'ast.literal_eval':http://docs.python.org/library/ast.html#ast-helpers – rubik
可以将空字典作为全局变量和本地变量传递。在这种情况下,'eval()'不能访问全局和本地命名空间,并且不能调用任意函数。这实际上很简单:'data = eval(“{%s}”%foo,{},{})'。如果有人试图运行恶意代码(例如,制作'foo =''a':os.unlink('/ etc/resolv.conf')“'),则找不到'os'模块。 – brandizzi
要使用ast.literal_eval
。例如:
>>> foo = "'totalteams': 10, 'totalrounds': 11"
>>> import ast
>>> ast.literal_eval("{%s}" % foo)
{'totalteams': 10, 'totalrounds': 11}
>>>
Edit:
嗯..上google-app-engine?您可能需要考虑使用在该环境中更容易解析的格式。 PyYAML是标准在那里,你可以考虑使用这种格式来代替:
>>> import yaml
>>> yaml.load("""
... totalteams: 10
... totalrounds: 11
... """)
{'totalteams': 10, 'totalrounds': 11}
>>>
不适用于Python 2.5 – rubik
因为字符串不是一本字典。你有两个选择:
做一个字典文字:
data = {'totalteams': 10, 'totalrounds': 11}
print data['totalteams']
有一个JSON字符串或数据类似的东西,如果你有一个字符串的工作:
# as F.J pointed out, json isn't a built-in in python 2.5 so you'll have to get simplejson or some other json library
import json
foo = '{"totalteams": 10, "totalrounds": 11}'
data = json.loads(foo)
print data['totalteams']
# or
foo = '"totalteams": 10, "totalrounds": 11'
data = json.loads('{%s}' % foo)
或者使用eval
像dminer的答案,但eval
应该是最后的手段。
谢谢。是eval更昂贵? – Jim
'eval()'是一种安全风险。 –
'json'不是2.5的内置函数,所以只有在使用simplejson或其他JSON模块时才能使用。另外,JSON对象需要双引号字符串,所以初始字符串需要转换为“{”totalteams“:10,”totalrounds“:11}''。 –
它可能不是那样强劲,但它的2.5兼容:
import re
foo = "'totalteams':10,'totalrounds':11"
m = re.compile("'(\w+)':(\d+)")
t = m.findall(foo)
然后你会得到你可以分解并压缩成字典
>>> a,b = zip(*t)
>>> a
('totalteams', 'totalrounds')
>>> b
('10', '11')
>>> d = dict(zip(list(a),list(b)))
>>> d
{'totalteams': '10', 'totalrounds': '11'}
>>>
信贷http://selinap.com/2009/02/unzip-a-python-list/元组的列表: :从来不知道你可以解压缩列表:)
可能的重复:http://stackoverflow.com/questions/988228/converting-a-string-to-dictionary –