Pradeeshnarayan
Pradeeshnarayan

Reputation: 1235

Python convert string to array assignment

In my application I am receiving a string 'abc[0]=123'

I want to convert this string to an array of items. I have tried eval() it didnt work for me. I know the array name abc but the number of items will be different in each time.

I can split the string, get array index and do. But I would like to know if there is any direct way to convert this string as an array insert. I would greately appreciate any suggestion.

Upvotes: 0

Views: 348

Answers (3)

georg
georg

Reputation: 214969

Here's a function for parsing urls according to php rules (i.e. using square brackets to create arrays or nested structures):

import urlparse, re

def parse_qs_as_php(qs):

    def sint(x):
        try:
            return int(x)
        except ValueError:
            return x

    def nested(rest, base, val):
        curr, rest = base, re.findall(r'\[(.*?)\]', rest)
        while rest:
            curr = curr.setdefault(
                sint(rest.pop(0) or len(curr)), 
                {} if rest else val)
        return base

    def dtol(d):
        if not hasattr(d, 'items'):
            return d
        if sorted(d) == range(len(d)):
            return [d[x] for x in range(len(d))]
        return {k:dtol(v) for k, v in d.items()}

    r = {}
    for key, val in urlparse.parse_qsl(qs):
        id, rest = re.match(r'^(\w+)(.*)$', key).groups()
        r[id] = nested(rest, r.get(id, {}), val) if rest else val
    return dtol(r)

Example:

qs = 'one=1&abc[0]=123&abc[1]=345&foo[bar][baz]=555'
print parse_qs_as_php(qs)
# {'abc': ['123', '345'], 'foo': {'bar': {'baz': '555'}}, 'one': '1'}

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599610

Your other application is doing it wrong. It should not be specifying index values in the parameter keys. The correct way to specify multiple values for a single key in a GET is to simply repeat the key:

http://my_url?abc=123&abc=456

The Python server side should correctly resolve this into a dictionary-like object: you don't say what framework you're running, but for instance Django uses a QueryDict which you can then access using request.GET.getlist('abc') which will return ['123', '456']. Other frameworks will be similar.

Upvotes: 0

avasal
avasal

Reputation: 14854

are you looking for something like

In [36]: s = "abc[0]=123"

In [37]: vars()[s[:3]] = []

In [38]: vars()[s[:3]].append(eval(s[s.find('=') + 1:]))

In [39]: abc
Out[39]: [123]

But this is not a good way to create a variable

Upvotes: 1

Related Questions