Search code examples
pythondictionary-comprehension

Convert String to Dictionary


I have a string

str = "Name John"

I want to change it to a dictionary.

{"Name":"John"}

How do I achieve this? I Have tried using comprehension but I get an error.

str = "Arjun 23344"
Name = {str.split()}

Error

Traceback (most recent call last):
  File "/home/daphney/Python/AGame.py", line 2, in <module>
    Name = {x.split()}
TypeError: unhashable type: 'list'

Solution

  • You can split:

    my_dict = {str.split(" ")[0]:str.split(" ")[1]}
    

    Note: If you have, say, Name John Smith and want the dict to be Name:Smith, then you can just change the [1] to [-1] to get the last indexed item.