Reputation: 16536
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?
Upvotes: 4
Views: 462
Reputation: 236140
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()))
Upvotes: 2