0

I have a .txt file (type string) {'A': 0, 'B': 2, 'C':0, ...} which I would like to convert to a dictionary (to be able to save all elements containing 0s in another file). I have found many codes, but in them key to be and value to be are separated with a comma, not : ( I always receive error message invalid syntax on :). I have tried to convert the string into a list, and convert this list into a dictionary, but did not manage...

with open("ab.txt", 'r') as f:
    filecontents = f.read().replace(",", "\n")
    filecontents.replace(":", ",")    # this does not work
    res = filecontents.strip('{}').split('\n')

Do you have any suggestions how to do the conversion? (or just save the elements containing 0 differently)?

Patrick Artner
  • 48,339
  • 8
  • 43
  • 63
  • Does this answer your question? [How do I serialize a Python dictionary into a string, and then back to a dictionary?](https://stackoverflow.com/questions/4342176/how-do-i-serialize-a-python-dictionary-into-a-string-and-then-back-to-a-diction) – user7313094 Dec 11 '20 at 19:37
  • I have tried json.load without success, will keep on trying... in reality it is a txt file. (Last error message from json.load: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)) Thanks for reply! – Black Black Dec 11 '20 at 19:52
  • `filecontents.replace(":", ",")` does work - you just do _nothing_ with the string it returns. It does not work in-place - it returns a modified string! – Patrick Artner Dec 11 '20 at 20:02
  • using json or `ast.literal_eval` would both work to convert your dict - see both other dupes for that. – Patrick Artner Dec 11 '20 at 20:04
  • error message from ast.literal_eval: 'a', 4 SyntaxError: invalid syntax right in the beginning with '. (node_or_string = parse(node_or_string, mode='eval') – Black Black Dec 11 '20 at 21:13
  • same error message with ast.literal after having changed the ' into "... with yaml: ValueError: not enough values to unpack (expected 2, got 1) – Black Black Dec 11 '20 at 21:19
  • and success with json.loads after having changed the ' into ". Thank you very much for the help! – Black Black Dec 11 '20 at 21:25

0 Answers0