Converting a string to dictionary in Python Value Error

python convert string to dictionary json
python split string into dictionary
convert string to dictionary python
convert string to dictionary python3
python create dictionary from string
convert list of string to dictionary python
python dictionary
convert to dict python

I have tried different options to convert a string to dictionary.

My string looks like this:

{'severity_label': 'Major', 'ne_reported_time': 1475424546, 'node_id': 54357, 'prob_cause_string': None}

When i use

 a_dict = dict([x.strip('{}').split(":"),]) 

it gives me an error:

Traceback (most recent call last):
  File "<pyshell#168>", line 1, in <module>
    a_dict = dict([x.strip('{}').split(":"),])
ValueError: dictionary update sequence element #0 has length 121; 2 is required

I am running this on Python3. Also tried various other options things not working. Any help appreciated.

Actually this is not JSON. This is a representation of a python object (like using the repr function).

The most safe way to convert this back to a python object is to use the ast.literal_eval function.

Python, Python | Convert key-value pair comma separated string into dictionary · Python | Convert a set into dictionary · Python - Filter dictionary values in heterogenous  Python | Convert string dictionary to dictionary Interconversions of data types have been discussed many times and have been quite a popular problem to solve. This article discusses yet another problem of interconversion of dictionary, in string format to a dictionary.

You should use json.loads

import json
a = '{"severity_label": "Major", "ne_reported_time": 1475424546, "node_id": 54357, "prob_cause_string": null}'
d = json.loads(a)

Note I replaced ' by " and None by null

Python program to create a dictionary from a string, Dictionary in python is a very useful data structure and at many times we see problems the string looks like dictionary as in python) then we can easily convert it to Dict = dict ((x.strip(), y.strip()) for x, y in (element.split( '-' ) for element in  Python dictionaries have keys that needn't be strings; therefore, when you write {a: b} you need the quotation marks around a if it's meant to be a string. ({1:2}, for instance, maps the integer 1 to the integer 2.)

Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval

import ast
str_of_dict = "{'key1': 'key1value', 'key2': 'key2value'}"
ast.literal_eval(str_of_dict)

will give output as actual Dictionary

{'key1': 'key1value', 'key2': 'key2value'}

This is easy as you like.

json — JSON encoder and decoder, If allow_nan is false (default: True ), then it will be a ValueError to serialize out of is converted into JSON, all the keys of the dictionary are coerced to strings. Python Dictionary to String. Let’s consider the following scenario. I am writing the program that stores data in a dictionary object. Still, this data needs to be saved at some point during a program execution and loaded back into the dictionary object when the program is rerun.

That string really is valid JSON, I think. Just use the json.loads functionality to get a dictionary.

5. Built-in Types, All other values are considered true — so objects of many types are always true. (Important exception: the Boolean operations or and and always return one of their Two methods support conversion to and from hexadecimal strings. For other containers see the built in dict and set classes, and the collections module. We can use ast.literal_eval() here to evaluate the string as a python expression. It safely evaluates an expression node or a string containing a Python expression.The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

19.2. json — JSON encoder and decoder, If allow_nan is False (default: True), then it will be a ValueError to serialize out of is converted into JSON, all the keys of the dictionary are coerced to strings. Given a list, write a Python program to convert the given list to dictionary such that all the odd elements have the key, and even number elements have the value. Since python dictionary is unordered, the output can be in any order.

String to Dictionary conversion in python, return dict((_convert(k), _convert(v)) for k, v. File "/usr/lib/python2.7/ast.py", line 79​, in _convert raise ValueError('malformed string') ValueError:  Python | Convert dictionary object into string Dictionary is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary.

Python JSON, Parse JSON - Convert from JSON to Python The result will be a Python dictionary. Example. Convert Python objects into JSON strings, and print the values:. Python JSON to string. Converting JSON string can be done by two methods: json.dumps() - preferred way for conversion. Always produce valid JSON string; str() - could produce invalid JSON string for some values; Example:

Comments
  • You got the right answer (using ast.literal_eval()) but you should really consider why you have a Python dictionary string representation in the first place. That is not a sane format to pass around information. Better use JSON or any other standard format. Or at least pickled data, as that is meant to be a serialization format.