Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to dictionary in python

Tags:

python

I have the following string :

str = "{application.root.category.id:2}"

I would like to convert the above to a dictionary data type in python as in :

dict = {application.root.category.id:2}

I tried using eval() and this is the error I got:

AttributeError: java package 'application' has no attribute "root"

My current python is of <2.3 and I cannot update the python to >2.3 .

Any solutions ?

like image 593
user170008 Avatar asked Aug 31 '25 01:08

user170008


1 Answers

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.)

So you can't just pass something of the sort you have to eval. You'll need to parse it yourself. (Or, if it happens to be easier, change whatever generates it to put quotation marks around the keys.)

Exactly how to parse it depends on what your dictionaries might actually look like; for instance, can the values themselves be dictionaries, or are they always numbers, or what? Here's a simple and probably too crude approach:

contents = str[1:-1]        # strip off leading { and trailing }
items = contents.split(',') # each individual item looks like key:value
pairs = [item.split(':',1) for item in items] # ("key","value"), both strings
d = dict((k,eval(v)) for (k,v) in pairs) # evaluate values but not strings
like image 149
Gareth McCaughan Avatar answered Sep 02 '25 14:09

Gareth McCaughan