Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python put string into dictionary

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.

like image 422
Rust Avatar asked Aug 29 '26 07:08

Rust


2 Answers

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

like image 151
JBernardo Avatar answered Aug 31 '26 21:08

JBernardo


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})
like image 35
Luce Avatar answered Aug 31 '26 19:08

Luce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!