-1

What is one of the pythonic ways to convert a string which has a built-in dictionary formatting into a dictionary? I have tried regex but it isn't quite there to be the right formatting .

string_dictable ="{""name"":""Andrew,Carnegie"",""short_name"":""And,Car"",
""YOB"":1835,""Citizen"":""Scottish""}"

All the extra quotation paddings seem to be the problem and so far I haven't been able to work around them.

My expected output is:

dicted_string ={"name":"Andrew, Carnegie","short_name":"And,Car","YOB":1835,"Citizen":"Scottish"}

I have also tried

ast.literal_eval (string_dictable)

to no avail.

EDIT: I haven't touched the original formatting and unfortunately, the original question cannot be clarified or modified. Thanks all for the contribution though. As I have said the regex solution got me this

{'{name': 'Andrew,Carnegie,short_name:And,Car,YOB:1835,Citizen:Scottish}'}

and it isn't exactly what I needed to do some work on.

Benyam
  • 61
  • 6
  • 2
    Where did you get that string in first place? Can't you make it better from the source? – nosklo Aug 10 '18 at 14:34
  • 2
    you can try `ast.literal_eval(yourstring.replace('""', '"'))` – nosklo Aug 10 '18 at 14:35
  • 1
    It looks like someone thinks that Python strings escape `"` characters by doubling up on them. That's not the case. String literals that are next to each other are automatically concatenated, so `"abc""123"` evaluates to `"abc1123"` – Patrick Haugh Aug 10 '18 at 14:37
  • 1
    Are you getting this from some other file in this format, or are you writing these string literals into the python file? If you are getting them from a file, could we see a line or two of that file? – Patrick Haugh Aug 10 '18 at 14:47

4 Answers4

0

Your string_dictable has syntax errors (it has two quotation marks where there should be one). Try this:

string_dictable = '{"name":"Andrew,Carnegie","short_name":"And,Car", "YOB":1835,"Citizen":"Scottish"}'
dict = ast.literal_eval (string_dictable)
brandonwang
  • 1,603
  • 10
  • 17
0

Solution using

json
module
import json
dicted_string = json.loads(string_dictable.replace('""','"')

There is no elegant way that I know of which will handle the double double quotes in the original string, otherwise the string is basically good json format.

If you are able to change the source of your string to eliminate the double double quotes ("") then you can simply feed string_dictable to json.loads to get a dictionary out of the string.

-1

Just replace "" with " and use eval() then. It's pretty easy, just like this:

string_dictable ='{""name"":""Andrew,Carnegie"",""short_name"":""And,Car"",""YOB"":1835,""Citizen"":""Scottish""}'
string_dictable = string_dictable.replace('""','"')
d = eval(string_dictable)

d is a valid dictionary.

Ildar Akhmetov
  • 1,331
  • 13
  • 22
  • If the input is being given as `string_dictable ="{""name"":""Andrew,Carnegie"",""short_name"":""And,Car"", ""YOB"":1835,""Citizen"":""Scottish""}"` then this solution doesn't work. Since you already replaced the outer " with ' which apparently is wrong (see my answer being downvoted) – J0hn Aug 10 '18 at 14:47
  • It's a bit weird that the answer is downvoted. The solution seems to be pretty easy and straightforward since the problem is just with the double quote character. – Ildar Akhmetov Aug 10 '18 at 14:48
  • @J0hn but string_dictable ="{""name"":""Andrew,Carnegie"",""short_name"":""And,Car"", ""YOB"":1835,""Citizen"":""Scottish""}" is not a correct Python expression... It means that the questions makes no sence. – Ildar Akhmetov Aug 10 '18 at 14:49
  • Exactly, this question requires some more information about where this input is coming from and why it's so incorrect. The question should likely be closed since it's impossible to solve with the current info given. – J0hn Aug 10 '18 at 14:51
  • @IldarAkhmetov It _is_ a valid Python statement. Did you try? – DYZ Aug 11 '18 at 04:50
  • @DYZ Which statement do you mean? – Ildar Akhmetov Aug 11 '18 at 05:32
  • The first statement in the original post. The one that you say "is not a correct Python expression." – DYZ Aug 11 '18 at 06:41
-2

Okay replacing this answer almost entirely but leaving the original below.

So from what I've gathered, the current issue is that the OP has a text file with the following inside of it: "{""name"":""Andrew,Carnegie"",""short_name"":""And,Car"",""YOB"":1835,""Citizen"":""Scottish""}"

So, when reading the file into python, this is what needs to happen:

f = open('stack.txt','r+') #I've made a text file with the above inside of it named stack.txt
for i in f:
    fixed = str(i).replace('"', "'")
    fixed = fixed.replace("''", '"')
    d = eval(fixed)

d will now be formatted as such: {"name":"Andrew,Carnegie","short_name":"And,Car","YOB":1835,"Citizen":"Scottish"}

The first fix changes it to: '{''name'':''Andrew,Carnegie'',''short_name'':''And,Car'',''YOB'':1835,''Citizen'':''Scottish''}'

Second run through fixes the '' issue: '{"name":"Andrew,Carnegie","short_name":"And,Car","YOB":1835,"Citizen":"Scottish"}'

Finally the eval turns it into a dictionary.

OLD POST IGNORE

Very easily using eval(string)

Here's a quick mock-up I did. Make sure to use similar syntax, and you should be good to go.

>>> String = '{"name":"Andrew,Carnegie","short_name":"And,Car", "YOB":1835,"Citizen":"Scottish"}'
>>> dictionary = eval(String)
>>> dictionary['name']
'Andrew,Carnegie'
>>> 

EDIT: Not sure why this is being downvoted so far, the eval() method is the easiest way to convert a string to dictionary, if the input can't be modified by OP then I can work on a solution but the issue is that the original string can't even be read by Python:

>>> string_dictable ="{""name"":""Andrew,Carnegie"",""short_name"":""And,Car"",
""YOB"":1835,""Citizen"":""Scottish""}"
SyntaxError: EOL while scanning string literal

So unless it's stored in a text file and the variable can be modified as it's input there's not much that can be done from a python standpoint.

J0hn
  • 570
  • 4
  • 19
  • Note that `string_dictable` in the above evaluates to `'{name:Andrew,Carnegie,short_name:And,Car,YOB:1835,Citizen:Scottish}'` – Patrick Haugh Aug 10 '18 at 14:36
  • @PatrickHaugh Not sure what you're getting at, I edited his syntax so that it's not wrong. If he needs to modify the input for it to work then he should clarify that. – J0hn Aug 10 '18 at 14:38
  • @timgeb the original syntax is literally impossible for python to handle, unless this is being pulled from a file (which OP hasn't stated how or why it's formatted as such) then there's nothing that can be done. – J0hn Aug 10 '18 at 14:44
  • @J0hn the string is presented here in its original formatting. It is part of a file I can't share here. – Benyam Aug 10 '18 at 15:02
  • Regardless, that helps to know you're taking this out of a file. Are you using a method like `f = open("file.txt', "r"')`? Furthermore, is it stored in the text file with the `string_dictable =` part, or just the messed up dictionary? I need EXACTLY how it's stored given to me so I can fix this for you. – J0hn Aug 10 '18 at 15:06
  • @Benyam see above – J0hn Aug 10 '18 at 15:11
  • @J0hn the original file has a lot more nested structure. I have simplified it to a segment which if solved would also be used for any level of nesting. By the way, both of the formats in your question are the same and yes it is originally in this format. I have done no formatting to the original string whatsoever. – Benyam Aug 10 '18 at 15:17
  • @Benyam Alright, see my replaced answer at the top for your solution then. – J0hn Aug 10 '18 at 15:38
  • @DYZ From the horse's mouth: "There are some cases where you have to use eval or exec. But they are rare. Using eval in your case is a bad practice for sure. I'm emphasizing on bad practice because eval and exec are frequently used in the wrong place." If you want to downvote me because I used eval() then give me how you would solve this problem so I can avoid it's use. – J0hn Aug 13 '18 at 12:45
  • `ast.literal_eval` is safe - and sufficient for this job. – DYZ Aug 13 '18 at 14:13