# Python3 code to convert # string to dictionary # Initializing String string = "{’ A’: 13, ’B’: 14,’ C’: 15} " # eval () convert string to dictionary Dict = eval (string) print ( Dict ) print ( Dict [ ’A’ ]) print ( Dict [ ’C’ ]) |
Output:
{’C’: 15,’ B’: 14, ’A’: 13} 13 15
Method # 2: Using generator expressions in Python
If we receive string input that does not completely resemble a dictionary object, then we can use generator expressions to convert it to a dictionary.
# Python3 code to convert # line to dictionary # Init ializing String string = "A - 13, B - 14, C - 15 " # Convert string to dictionary Dict = dict ((x.strip (), y.strip ()) for x, y in (element.split ( ’-’ ) for element in string.split ( ’,’ ))) print ( Dict ) print ( Dict [ ’A’ ]) print ( Dict [ ’C’ ]) |
Exit :
{’C’:’ 15’, ’A’:’ 13’, ’B’:’ 14’} 13 15
The above code does not convert integers to int type,
if there are integer keys, then only line 8 will work
string = "11 - 13, 12 - 14, 13 - 15" Dict < code class = "keyword"> = dict ((x.strip (), int (y.strip ())) for x , y in (element.split ( ’-’ ) for element in string.split ( ’,’ ))) print ( Dict ) |
Exit:
{’13’: 15,’ 12’: 14, ’11’: 13}
Python program to create a dictionary from a string __dict__: Questions
Python program to create a dictionary from a string Python functions: Questions