我的表格中有字符串
[3339:1.6101369,1062:1.5,5751:1.5,6376:1.5, ... ]
我想迭代逗号分隔的键值对。最好或最短的方法是什么?
答案 0 :(得分:8)
s = "[3339:1.6101369,1062:1.5,5751:1.5,6376:1.5]"
s = s.strip("[]") # Drop the brackets
for kv in s.split(","):
key, value = kv.split(":")
print key, value
或者,您可以将其转换为字典(在剥离括号后):
d = dict(kv.split(":") for kv in s.split(","))
然后遍历字典:
for key in d:
print key, d[key]
答案 1 :(得分:3)
d = ast.literal_eval('{' + s[1:-1] + '}')