Victor Di Victor Di - 1 year ago 103
Python Question

not standard splitting

I have string value like:

a='[-sfdfj aidjf -dugs jfdsif -usda [[s dfdsf sdf]]]'

I want to transform "a" into dictionary: the strings with preceding "-" character should be keys and what goes after the space should be values of the key preceding it.
If we are working with "a", then what I want is the resulting dictionary like:

dict_a={'-sfdfj': 'aidjf', '-dugs': 'jfdsif', '-usda': '[[s dfdsf sdf]]'}

This would be simple if not the last value('[[s dfdsf sdf]]'), it contains the spaces. Otherwise I would just strip the external brackets and split the "a", then convert the resulting list into dict_a, but alas the reality is not on my side.
Even if I get the list like:

list_a=['-sfdfj', 'aidjf', '-dugs', 'jfdsif', '-usda', '[[s dfdsf sdf]']

this would be enough.
Any help will be appreciated.

Answer Source

You can split the string by '-' and then add the '-' back.

a = '[-sfdfj aidjf -dugs jfdsif -usda [[s dfdsf sdf]]]'
a = a[1:-1]    # get ride of the start and end []
sections = a.split('-')
dict_a = {}
for s in sections:
    s = s.strip()
    if len(s) == 0:
    key_value = s.split(' ')   # split key value by space
    key = '-' + key_value[0]         # the first element is key
    value = ' '.join(key_value[1:])    # the lefe are value
    dict_a[key] = value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download