4

I'm sure that this is both extremely easy and a combination of other questions on SO but I can't find the right answer.

I have a unicode string: u"word1 word2 word3..." It will always be in the same format. I want to parse it into a dictionary that will always have the same keys:

"key1:word1 key2:word2 key3:word3..."

How do I do this?

asked Oct 23, 2011 at 14:42

1 Answer 1

2

Try this:

keys = ['key1', 'key2', 'key3']
words = u'word1 word2 word3'
vals = words.split()
d = dict(zip(keys, vals))

And then, if you want to retrieve the key/value pairs in a string like the one in your example:

' '.join(sorted(k + ':' + v for k,v in d.items()))
answered Oct 23, 2011 at 14:47
Sign up to request clarification or add additional context in comments.

4 Comments

Ok that worked perfectly. Dumb follow-up: if I have two values post-split that I want to combine -- if I want word3 and word4 to really be a single word separated by a space -- how do I do that?
You could use a different separator, say a ',' and split using that separator
I found an answer here: stackoverflow.com/questions/1142851/…, though let me make it more complicated: what if I want words 3 and 4 to preserve with a space between them?
Got it: x[2:4] = [''.join(x[2]+ " " + x[3])]

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.