Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a dictionary string?

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?

like image 502
Lalit Singh Avatar asked Apr 08 '15 12:04

Lalit Singh


People also ask

How do you decode a dictionary in Python?

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.

How do you turn a dictionary into a string?

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.


2 Answers

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'
like image 132
thefourtheye Avatar answered Sep 21 '22 21:09

thefourtheye


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.

like image 37
dcrosta Avatar answered Sep 24 '22 21:09

dcrosta