Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through parts of a string

I have string in the form

[3339:1.6101369,1062:1.5,5751:1.5,6376:1.5,  ...  ]

I want to iterate through the comma separated key-value pairs. What is the best or shortest way to do this?

like image 667
Thomas Avatar asked Feb 14 '11 22:02

Thomas


2 Answers

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

Alternatively, you could convert this into a dictionary (after stripping the brackets):

d = dict(kv.split(":") for kv in s.split(","))

and then iterate over the dictionary:

for key in d:
    print key, d[key]
like image 149
Sven Marnach Avatar answered Sep 28 '22 18:09

Sven Marnach


d = ast.literal_eval('{' + s[1:-1] + '}')
like image 23
Mark Byers Avatar answered Sep 28 '22 18:09

Mark Byers