Reputation: 19329
With the string variable being:
text = 'red~5~cat'
I would like to split it by '~' character and store the values as a dictionary. I have reserved the names for the keys and they are:
key_names = ['color', 'number', 'pet']
I wonder if there is a way to pack the result of splitting as a dictionary below?
{'color':'red', 'number':5, 'pet':'cat'}
Upvotes: 1
Views: 5159
Reputation: 6655
What about simply zipping your keys with the result of split, as follows
>>> dict(zip(key_names, text.split('~'))
{'pet': 'cat', 'number': '5', 'color': 'red'}
Upvotes: 9
Reputation: 1608
You could use zip function:
>>> dictionary = dict(zip(key_names, text.split('~')))
>>> dictionary
{'pet': 'cat', 'number': '5', 'color': 'red'}
Upvotes: 2