4

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 ?

4
  • 1
    What should be the key of the dictionary item? Commented Jun 11, 2012 at 11:10
  • 1
    can you explain the java package thing? Commented Jun 11, 2012 at 11:12
  • 1
    Do you want {application.root.category.id: 2} or {"application.root.category.id": 2}? Your problem is that application.root.category.id cannot be evaluated. Commented Jun 11, 2012 at 11:22
  • This question isn't in any way version-specific. Commented Aug 14, 2022 at 18:12

3 Answers 3

5

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

2 Comments

For security reasons, I'd rather use int(v) or eval(v,{},{}) instead of the plain eval(v). Compare eval("os.remove('/tmp/a')", {}, {}) ("name 'os' is not defined") against eval("os.remove('/tmp/a')") ("No such file or directory: '/tmp/a'").
Yes. Generally using eval (especially its simple one-arg form) is a bad, bad idea. I just lazily did it because the OP did :-).
3

First, 'dict' is the type name so not good for the variable name.

The following, does precisely as you asked...

a_dict = dict([str.strip('{}').split(":"),])

But if, as I expect, you want to add more mappings to the dictionary, a different approach is required.

Comments

0

Suppose I have a string

str='{1:0,2:3,3:4}'
str=str.split('{}')
mydict={}
for every in str1.split(','):
    z=every.split(':')
    z1=[]
    for every in z:
        z1.append(int(every))
    for k in z1:
        mydict[z1[0]]=z1[1]

output: mydict {1: 0, 2: 1, 3: 4}

Comments

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.