Help with parsing a list
MRAB
python at mrabarnett.plus.com
Wed Dec 16 18:21:05 EST 2009
J wrote:
> Hi all,
>
> I need some help in turning a list into a dictionary...
>
> The list looks something like this:
>
> ['key1: data1','key2: data2','key3: data3',' key4: ',' \tdata4.1','
> \tdata4.2',' \tdata4.3','key5: data5']
>
> and it's derived from output (via subprocess.Popen) that in a terminal
> would look like this:
>
> key1: data1
> key2: data2
> key3: data3
> key4:
> data4.1
> data4.2
> data4.3
> key5: data5
>
> So what I want to do is turn this into a dictionary that looks like this:
>
> {'key1':'data1','key2':'data2','key3':'data3','key4':['data4.1','data4.2','data4.3'],'key5':'data5']
>
> So the problem I am having is just with the key 4 stuff... right now,
> I'm looking at something like this (pseudocode because I'm still
> trying to work this out)
>
> loop through list
> if item is 'flags'
> make flags the key
> add every following item until item + 1 does not start with \t
> partition item where item[0] is key and item[2] is value
>
> Sorry for not having actual code yet... I am still trying to work out
> how to handle this on paper before actually writing code.
>
> And no, it's not a homework assignment ;-) just a small part of a
> project I'm working on.
>
Speaking personally, I'd make all of the values lists, instead of some
them lists and others strings.
You could split each list item into a key/value pair. Some items would
have a key and an empty value, eg. ['key4', ''], some only a value, eg.
['data4.1']. If there's a key then add the key and an empty list to the
dict; if there's a value then add it to the list for the key; if there's
no key then use the previous key.
More information about the Python-list
mailing list