xxxxxxxxxx
import json
data_str = '{"msg":"hi","username":"admin"}'
data_dict = json.loads(data_str)
print(data_dict)
xxxxxxxxxx
>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
xxxxxxxxxx
the_string = "{'hi': 'lol', 'us': 'no'}"
the_dict = eval(the_string)
print(the_dict)
print(type(the_dict))
xxxxxxxxxx
# Python3 code to demonstrate
# convert dictionary string to dictionary
# using json.loads()
import json
# initializing string
test_string = '{"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}'
# printing original string
print("The original string : " + str(test_string))
# using json.loads()
# convert dictionary string to dictionary
res = json.loads(test_string)
# print result
print("The converted dictionary : " + str(res))
xxxxxxxxxx
>>> D1={'1':1, '2':2, '3':3}
>>> s=str(D1)
>>> import ast
>>> D2=ast.literal_eval(s)
>>> D2
{'1': 1, '2': 2, '3': 3}
xxxxxxxxxx
# python3
import ast
byte_str = b"{'one': 1, 'two': 2}"
dict_str = byte_str.decode("UTF-8")
mydata = ast.literal_eval(dict_str)
print(repr(mydata))
xxxxxxxxxx
# Python3 code to demonstrate
# convert dictionary string to dictionary
# using json.loads()
import json
# initializing string
test_string = '{"Nikhil" : 1, "Akshat" : 2, "Akash" : 3}'
# printing original string
print("The original string : " + str(test_string))
# using json.loads()
# convert dictionary string to dictionary
res = json.loads(test_string)
# print result
print("The converted dictionary : " + str(res))
xxxxxxxxxx
# Python3 code to demonstrate working of
# Convert key-value String to dictionary
# Using dict() + generator expression + split() + map()
# initializing string
test_str = 'gfg:1, is:2, best:3'
# printing original string
print("The original string is : " + str(test_str))
# Convert key-value String to dictionary
# Using dict() + generator expression + split() + map()
res = dict(map(str.strip, sub.split(':', 1)) for sub in test_str.split(', ') if ':' in sub)
# printing result
print("The converted dictionary is : " + str(res))