I am trying to convert a file to a dictionary here is the contents of the file,

Name: DragonMastur;
Hand: None;
Inventory: {"Gold": 0, "Brush": 0, "Twig": 0, "Sapling": 0, "Metal Axe": 0, "Grass": 0, "Metal Pickaxe": 0, "Metal": 0, "Log": 0, "Diamond": 0, "Stick": 0, "Stone": 0, "Wheat": 0, "Stone Axe": 0, "Stone Pickaxe": 0};
Health: 100;

And here is my code for conversion,

file = open(self.curDir+"/playerstats.txt", "r")
print(file.read().strip().split(";\n"))
print(editor.join(file.read().strip().split(";\n"), ": "))
print(editor.join(file.read().strip().split(";\n"), ": ").split(": "))
self.playerinfo = editor.dictfromlist(editor.join(file.read().strip().split(";\n"), ": ").split(": "))
self.playerinfo["Inventory"] = ast.literal_eval(self.playerinfo["Inventory"].strip().strip(";"))
file.close()
print(self.playerinfo)

The "self.curDir" is the directory with all my files, it opens the file fine but it returns a blank string and/or list after I try to convert it.

And here is the funtion in my custom moudle "editor",

def join(self, list, joiner="\n"):
    returnstr = ""
    for x in list:
        returnstr += str(x) + joiner
    returnstr = returnstr[:-int(len(joiner))]
    return returnstr

Thanks all help helps.

Edited 1 Year Ago by DragonMastur

I am trying to convert a file to a dictionary here is the contents of the file,

You can data keep structure bye using serialization,
then you don't have to struggle to recreate structure from a string.
JSON is preferably over Pickle.

import json

record = {
'Name': 'DragonMastur',
'Hand': None,
'Inventory': {"Gold": 0, "Brush": 0, "Twig": 0, "Sapling": 0,
    "Metal Axe": 0, "Grass": 0, "Metal Pickaxe": 0, "Metal": 0,
    "Log": 0, "Diamond": 0, "Stick": 0, "Stone": 0, "Wheat": 0,
    "Stone Axe": 0, "Stone Pickaxe": 0},
'Health': 100
    }

with open("my_file.json", "w") as f_out:
    json.dump(record, f_out)
with open("my_file.json") as f_obj:
    saved_record = json.load(f_obj)

Test that saved_record still works as a dictionary.

>>> type(saved_record)
<class 'dict'>
>>> saved_record['Name']
'DragonMastur'
>>> saved_record['Inventory']
{'Brush': 0,
 'Diamond': 0,
 'Gold': 0,
 'Grass': 0,
 'Log': 0,
 'Metal': 0,
 'Metal Axe': 0,
 'Metal Pickaxe': 0,
 'Sapling': 0,
 'Stick': 0,
 'Stone': 0,
 'Stone Axe': 0,
 'Stone Pickaxe': 0,
 'Twig': 0,
 'Wheat': 0}
>>> saved_record['Inventory']['Gold']
0

Edited 1 Year Ago by snippsat

You can also use collections.OrderedDict instead of dict in the record in order to preserve the items' order. Use json.load(f_obj, object_pairs_hook=OrderedDict).

This article has been dead for over six months. Start a new discussion instead.