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?

Amit Verma
  • 40,709
  • 21
  • 93
  • 115
Lalit Singh
  • 329
  • 1
  • 2
  • 9

2 Answers2

17

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'
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
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.

dcrosta
  • 26,009
  • 8
  • 71
  • 83