Iterate over parts of a string

I have a line in the form

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

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

+4
source share
2 answers
 d = ast.literal_eval('{' + s[1:-1] + '}') 
+3
source
 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 can convert this to a dictionary (after removing the brackets):

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

and then iterate through the dictionary:

 for key in d: print key, d[key] 
+7
source

Source: https://habr.com/ru/post/1339747/


All Articles