I am trying to convert a string to a dictionary with dict
function, like this
import json
p = "{'id':'12589456'}"
d = dict(p)
print d['id']
But I get the following error
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Why does it fail? How can I fix this?
Python string method decode() decodes the string using the codec registered for encoding. It defaults to the default string encoding. We use it to convert the bytecode value into normal asci values by supplying ascii as the parameter to the decode function.
To convert a dictionary to string in Python, use the json. dumps() function. The json. dumps() is a built-in function that converts a Python object into a json string.
What you have is a string, but dict
function can only iterate over tuples (key-value pairs) to construct a dictionary. See the examples given in the dict
's documentation.
In this particular case, you can use ast.literal_eval
to convert the string to the corresponding dict
object, like this
>>> p = "{'id':'12589456'}"
>>> from ast import literal_eval
>>> d = literal_eval(p)
>>> d['id']
'12589456'
Since p
is a string containing JSON (ish), you have to load it first to get back a Python dictionary. Then you can access items within it:
p = '{"id":"12589456"}'
d = json.loads(p)
print d["id"]
However, note that the value in p
is not actually JSON; JSON demands (and the Python json
module enforces) that strings are quoted with double-quotes, not single quotes. I've updated it in my example here, but depending on where you got your example from, you might have more to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With