3

I want to convert a string into a dictionary. I saved this dictionary previously in a text file.

The problem is now, that I am not sure, how the structure of the keys are. The values are generated with Counter(dictionaryName). The dictionary is really large, so I cannot check every key to see how it would be possible.

The keys can contain simple quotes like ', double quotes ", commas and maybe other characters. So is there any possibility to convert it back into a dictionary?

For example this is stored in the file:

Counter({'element0':512, "'4,5'element1":50, '4:55foobar':23,...})

I found previous solutions with for example json, but I have problems with the double quotes and I cannot simply split for the commas.

6
  • 2
    I do not understand what you are trying to accomplish, and indeed, what you are even working with exactly... What, exactly is stored in a file? How did you "save the dictionary"? Did you literally just write the string representation to a file?That would be your first mistake - you should have used one of the many available serialization formats. Commented Sep 1, 2017 at 16:34
  • 1
    so you have the dictionary in text form ? and you want to convert it into dictionary? Commented Sep 1, 2017 at 16:36
  • @Mohsen_Fatemi yes I stored it in a text file. It took a lot of hours to get the dictionary, so I wanted to save it in a file. But I didn't expect, that it would contain double quotes etc. Commented Sep 1, 2017 at 16:38
  • 1
    Again, that is your first problem. You should have considered beforehand how you were going to serialize your data. Python has a pickle module that would have made this trivial. Just use eval and then use pickle to properly serialize your object. Commented Sep 1, 2017 at 16:39
  • If it is your data and you used something like repr to write that to the file, just use eval to reverse the process. As others have said, it is better to fix the problem in how the file was created as use cPickle to store the data. Commented Sep 1, 2017 at 16:41

4 Answers 4

3

If you trust the source, load from collections import Counter and eval() the string

Sign up to request clarification or add additional context in comments.

Comments

2

How about something like:

>> from collections import Counter
>> line = '''Counter({'element0':512, "'4,5'element1":50, '4:55foobar':23})'''
>> D = eval(line)
>> D
 Counter({"'4,5'element1": 50, '4:55foobar': 23, 'element0': 512})

Comments

1

You could remove the Counter( and ) parts, then parse the rest with ast.literal_eval as long as it only involves basic Python data types:

import ast

def parse_Counter_string(s):
    s = s.strip()
    if not (s.startswith('Counter(') and s.endswith(')')):
        raise ValueError('String does not match expected format')
    # Counter( is 8 characters
    # 12345678
    s = s[8:-1]
    return Counter(ast.literal_eval(s))

In the future, I recommend picking a different way to serialize your data.

Comments

0

you can use demjson library for doing this, you can have the text directly in your program

import demjson

counter = demjson.decode("enter your text here")

if it is in the file ,you can do the following steps :

WD = dirname(realpath(__file__))
file = open(WD, "filename"), "r")
counter = demjson.decode(file.read())
file.close()

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.