2

I'm trying to make small app that would calculate charge weight based on stored dict of materials/concentrations.
From time to time the dict needs to be updated and stored for future use.

Below snippet asks a user to provide new values for the dict and then updates it.

baseDict={'a':10, 'b':20, 'c':30, 'd':40}
def updateDict(key, value):
    temp = {key : value}
    baseDict.update(temp)
    return baseDict

key = str(input('Enter key\n'))
value = input('Enter value\n')
baseDict = updateDict(key, value)

The problem is that when the shell is re-started, the baseDict returns to the original values.
I found solutions for similar question from ~ 2010, but they use Pickle, shelve, JSON to store/retrieve the dict in a separate file and load it every time the code is run.

I'm planning to turn the code into a small .exe file to be ran on a py-less computer.
Any suggestions on how to make baseDict stay updated in such environment would be greatly appreciated.

Thank you!

  • 1
    json is part of the core python library. Why wouldn't you want to use it? – John Gordon Jan 13 '19 at 03:54
  • Thank you for comment, John. I want to make program as self-contained as I can. Can I use JSON and still turn the code into .exe? what about adding GUI with tkinter before exe? – Smith788483 Jan 13 '19 at 03:55
  • It looks like you wabt to mix user data and code. That's not a good idea. – Klaus D. Jan 13 '19 at 04:29

3 Answers3

0

You could save it to txt, then load it back.

So run a code by itself, like below:

with open('test.txt','w') as f:
    f.write("{'a':10, 'b':20, 'c':30, 'd':40}")

Then after that, run another module with the below code:

import ast
with open('test.txt','r') as f:
    baseDict=ast.literal_eval(f.read().rstrip())

def updateDict(key, value):
    temp = {key : value}
    baseDict.update(temp)
    return baseDict

key = str(input('Enter key\n'))
value = input('Enter value\n')
baseDict = updateDict(key, value)
with open('test.txt','w') as f:
    f.write(str(baseDict))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

As I know, the only way to keep changes of that kind is using local storage. It could be with Jsons, text files, databases, even you can create your own encoded type of file. The majority of apps need to be installed though, maybe encripting your data and storing it in secret files in a directory thta the app creates in the installation process, could be your option.

0

Using json or pickle is better than saving plaintext and ast.literal_evaling it. I would recommend json:

For json, first run this once:

import json

with open('baseDict.json', 'w') as f:
    json.dump({'a':10, 'b':20, 'c':30, 'd':40}, f)

Then:

import json

with open('baseDict.json','r') as f:
    baseDict = json.load(f)

# your code

with open('baseDict.json', 'w') as f:
    json.dump(baseDict, f)

See here for why json is better than ast.literal_eval.

iz_
  • 15,923
  • 3
  • 25
  • 40