8

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?

0

2 Answers 2

19

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'
Sign up to request clarification or add additional context in comments.

Comments

1

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.

9 Comments

Basically you solved a different problem and recommend that to OP?
p is a string containing JSON (ish) - No it is not.
@LalitSingh json.loads will not work for you. It will work only with JSON strings. What you have is not a JSON string.
what is difference between "{'id':'12589456'}" and '{"id":"12589456"}'
@LalitSingh JSON keys can have only double quotes. Single quotes are not valid JSON.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.