Split unicode string in python into dictionary

I am sure it is very simple, and a combination of other questions on SO, but I can not find the right answer.

I have a line in Unicode: u"word1 word2 word3..." It will always be in the same format. I want to analyze it in a dictionary that will always have the same keys:

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

How to do it?

+4
source share
1 answer

Try the following:

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

And then, if you want to get key / value pairs in a string similar to the one indicated in your example:

 ' '.join(sorted(k + ':' + v for k,v in d.items())) 
+2
source

All Articles