Convert string type array to array
<p>I have  this:</p>

<pre><code>[s[8] = 5,

 s[4] = 3,

 s[19] = 2,

 s[17] = 8,

 s[16] = 8,

 s[2] = 8,

 s[9] = 7,

 s[1] = 2,

 s[3] = 9,

 s[15] = 7,

 s[11] = 0,

 s[10] = 9,

 s[12] = 3,

 s[18] = 1,

 s[0] = 4,

 s[14] = 5,

 s[7] = 4,

 s[6] = 2,

 s[5] = 7,

 s[13] = 9]
</code></pre>

<p>How can I turn this into a python array where I can do <code>for items in x:</code> ?</p>

<p>An easy way, although less efficient than Kevin's solution (without using regular expressions), would be the following (where <code>some_array</code> is your string):</p>

<pre><code>sub_list = some_array.split(',')
some_dict = {}

for item in sub_list:
    sanitized_item = item.strip().rstrip().lstrip().replace('=', ':')

    # split item in key val
    k = sanitized_item.split(':')[0].strip()
    v = sanitized_item.split(':')[1].strip()

    if k.startswith('['):
        k = k.replace('[', '')

    if v.endswith(']'):
        v = v.replace(']', '')

    some_dict.update({k: int(v)})

print(some_dict)
print(some_dict['s[9]'])
</code></pre>

<p>Output sample:</p>

<pre><code>{'s[5]': 7, 's[16]': 8, 's[0]': 4, 's[9]': 7, 's[2]': 8, 's[3]': 9, 's[10]': 9, 's[15]': 7, 's[6]': 2, 's[7]': 4, 's[14]': 5, 's[19]': 2, 's[17]': 8, 's[4]': 3, 's[12]': 3, 's[11]': 0, 's[13]': 9, 's[18]': 1, 's[1]': 2, 's8]': 5}
7
</code></pre>

python python-2.7