alphanumeric
alphanumeric

Reputation: 19329

How to split string and store value as dictionary with predifined keys

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

Answers (2)

keepAlive
keepAlive

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

Yaroslav Surzhikov
Yaroslav Surzhikov

Reputation: 1608

You could use zip function:

>>> dictionary = dict(zip(key_names, text.split('~')))
>>> dictionary
{'pet': 'cat', 'number': '5', 'color': 'red'}

Upvotes: 2

Related Questions