6 examples of 'python str to dict' in Python

Every line of 'python str to dict' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
37def str2dict(dictstr):
38 """
39 @brief Convert string to dictionary
40 """
41 _dict = ast.literal_eval(dictstr)
42 if not isinstance(_dict, dict):
43 _dict = ast.literal_eval(dictstr.replace('"', ''))
44 if not isinstance(_dict, dict):
45 _dict = ast.literal_eval(dictstr.replace("'", ""))
46 if not isinstance(_dict, dict):
47 raise Exception("Cannot convert given string (%s) to dictionary." % (dictstr, ))
48 return _dict
93def py_str(py):
94 '''Turns a python value into a string of python code
95 representing that object'''
96 def maybe_str(s):
97 return s if isinstance(s, str) and '(' in s else repr(s)
98
99 if type(py) is dict:
100 return '{' + ', '.join(
101 [repr(k) + ': ' + maybe_str(py[k]) for k in py]) + '}'
102 if not isinstance(py, basestring):
103 return repr(py)
104 else:
105 return py
77def strToDict(string):
78 try:
79 return ast.literal_eval(string)
80 except ValueError as e:
81 logger.log(CUSTOM_LOGGING.ERROR, "conv string failed : %s" % e)
13def todict(obj):
14 res = {}
15 for key in obj:
16 if type(obj[key]) is dict:
17 subdict = todict(obj[key])
18 for k in subdict:
19 res[k] = subdict[k]
20 else:
21 res[key] = obj[key]
22 return res
25def python_to_json(python_data):
26 '''Convert python data (tuple, list, dict, etc) into json string'''
27 json_str = json.dumps(python_data, indent=4)
28 return json_str
13def to_dict(value):
14 if hasattr(value, 'as_dict'):
15 return value.as_dict()
16 return dict(value)

Related snippets