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
fox
16.7k22 gold badges61 silver badges85 bronze badges
1 Answer 1
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
Óscar López
237k38 gold badges321 silver badges391 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
fox
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?
Óscar López
You could use a different separator, say a ',' and split using that separator
fox
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?
fox
Got it:
x[2:4] = [''.join(x[2]+ " " + x[3])]lang-py