1

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'}

2 Answers 2

9

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'}
2

You could use zip function:

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.