mwaks
mwaks

Reputation: 389

Python Convert string to dict

I have a string :

'{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}' 

and would like to convert it to

{
  "tomatoes" : "5" , 
  "livestock" :"{"cow" : "5" , "sheep" :"2" }"
}

Any ideas ?

Upvotes: 16

Views: 51860

Answers (4)

cjor
cjor

Reputation: 609

This has been settled in 988251 In short; use the python ast library's literal_eval() function.

import ast
my_string = "{'key':'val','key2':2}"
my_dict = ast.literal_eval(my_string)

Upvotes: 24

innisfree
innisfree

Reputation: 2485

Here is my answer:

dict_str = '{tomatoes: 5, livestock: {cow: 5, sheep: 2}}'

def dict_from_str(dict_str):    

    while True:

        try:
            dict_ = eval(dict_str)
        except NameError as e:
            key = e.message.split("'")[1]
            dict_str = dict_str.replace(key, "'{}'".format(key))
        else:
            return dict_


print dict_from_str(dict_str)

My strategy is to convert the dictionary str to a dict by eval. However, I first have to deal with the fact that your dictionary keys are not enclosed in quotes. I do that by evaluating it anyway and catching the error. From the error message, I extract the key that was interpreted as an unknown variable, and enclose it with quotes.

Upvotes: -2

zwer
zwer

Reputation: 25779

The problem with your input string is that it's actually not a valid JSON because your keys are not declared as strings, otherwise you could just use the json module to load it and be done with it.

A simple and dirty way to get what you want is to first turn it into a valid JSON by adding quotation marks around everything that's not a whitespace or a syntax character:

source = '{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'

output = ""
quoting = False
for char in source:
    if char.isalnum():
        if not quoting:
            output += '"'
            quoting = True
    elif quoting:
        output += '"'
        quoting = False
    output += char

print(output)  #  {"tomatoes" : "5" , "livestock" :{"cow" : "5" , "sheep" :"2" }}

This gives you a valid JSON so now you can easily parse it to a Python dict using the json module:

import json

parsed = json.loads(output)
# {'livestock': {'sheep': '2', 'cow': '5'}, 'tomatoes': '5'}

Upvotes: 6

Natesh bhat
Natesh bhat

Reputation: 13192

What u have is a JSON formatted string which u want to convert to python dictionary.

Using the JSON library :

import json
with open("your file", "r") as f:
    dictionary =  json.loads(f.read());

Now dictionary contains the data structure which ur looking for.

Upvotes: 0

Related Questions