Skip to content Skip to sidebar Skip to footer

Converting A String To Dictionary In 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.categ

Solution 1:

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:valuepairs = [item.split(':',1) for item in items] # ("key","value"), both stringsd = dict((k,eval(v)) for (k,v) in pairs) # evaluate values but not strings

Solution 2:

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.

Solution 3:

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}

Post a Comment for "Converting A String To Dictionary In Python"