Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 466
mwaks Avatar asked Dec 05 '17 22:12

mwaks


People also ask

Can you convert a string to a dictionary in Python?

You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.

Can we convert string into dictionary?

Dictionary is an unordered collection in Python which store data values like a map i.e., key:value pair. In order to convert a String into a dictionary, the stored string must be in such a way that key:value pair can be generated from it.

Can string be used as key dictionary in Python?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.


2 Answers

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)
like image 75
cjor Avatar answered Oct 06 '22 20:10

cjor


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'}
like image 30
zwer Avatar answered Oct 06 '22 20:10

zwer