0

In my python program, I have a list of keys and values that are added to a text file and I need to be able to extract this string list and turn it into a dictionary.

For example:

    counter = 0
    add = str(counter)
    counterDict = UserID + ": " + add + ", "
    counter = counter + 1

#This should make counterDict look like: ""Smi39119": 0, "Joh38719": 1, " etc.

    f = open("Dictionaries.txt","a")
    f.write(counterDict)
    f.close()

#Then I would like to be able to open the file and turn that string into a dictionary

    f = open("Dictionaries.txt","r")
    string = f.read()

#This way 'string' should still be a string, but look like this: "{"Smi39119": 0, "Joh38719": 1, }"

I do not know if this is possible, but if it is, all solutions would be greatly appreciated.

1 Answers1

0

I'm guessing you are trying to save a dictionary to a file, * enter *: json file system, you don't need to convert your dictionary to string, let json do it for you to dump it into a string.

import json

f = open("Dictionaries.json","a")
f.write(json.dumps(your_dictionary))
f.close()

# load it and use it like a dictionary

f = open("Dictionaries.json","r")
your_dictionary = json.loads(f.read())

also read Writing a dict to txt file and reading it back?

cheers!

P.hunter
  • 1,345
  • 2
  • 21
  • 45
  • 1
    It would make more sense here to use `json.dump` and `json.load` to write and read from the file directly. – Nathan Vērzemnieks Apr 21 '19 at 16:37
  • The difference is much notable in python 3, I guess? https://stackoverflow.com/questions/36059194/what-is-the-difference-between-json-dump-and-json-dumps-in-python – P.hunter Apr 22 '19 at 06:25
  • 1
    As it says in that very answer, "If you want to dump the JSON into a file/socket or whatever, then you should go for `dump()` If you only need it as a string then use `dumps()`." Similarly there's no point in doing `json.loads(f.read())` when you can just do `lson.load(f)`. – Nathan Vērzemnieks Apr 22 '19 at 15:26