i am working on a program and I need to access a dicionary from another file, which I know how to do.I also need to be able to append the same dictionary and have it saved in its current form to the other file.
is there anyway to do this?
EDIT:
the program requires you to log in. you can create an account, and when you do it needs to save that username:password you entered into the dictionary. The way I had it, you could create an account, but once you quit the program, the account was deleted.
You can store and retrieve data structures using the pickle module in python, which provides object serialisation.
Save the dictionary
import pickle
some_dict = {'this':1,'is':2,'an':3,'example':4}
with open('saved_dict.pkl','w') as pickle_out:
pickle.dump(some_dict,pickle_out)
Load the dictionary
with open('saved_dict.pkl.'r') as pickle_in:
that_dict_again = pickle.load(pickle_in)
Related
I am trying to break my Python script into multiple .py files. In sf_opps.py file I have all the login credentials and a query that fetches the data with REST API call. The data is stored in sf_prod_data variable. How can I access this variable that contains the data I need from another .py file?
I need to loop through the sf_prod_data and I don't want to use classes as all of my code are mostly loops, so need to know how to access the variables with stored data in it from different .py files.
I have tried:
import sf_opps
print(sf_prod_data)
sf_prod_data is Undefined
Either:
from sf_opps import sf_prod_data
print(sf_prod_data)
or:
import sf_opps
print(sf_opps.sf_prod_data)
Further reading: python tutorial on modules
I created a JSON file to pass my required data to a web page. Everything is working perfectly. But Whenever I refresh or repeat the action on the same file, JSON send double, triple and so on. I think I need to clear the JSON file whenever I enter into the coding for api action to pass JSON file. How can I do it on Python.
#app.route('/patient_cap')
def Patient_cap_mat():
global numofCapability, MaxNumDis,capsArray,ListofPatCapability
column_array=[]
df2 = pd.read_csv('./datafiles/label_network.dat', sep='\s+', header=None)
.
.// set of coding for required values
.
.
for i in range(len(result_array)):
eachpatient=CapabilityMat(result_array[i],df.loc[i].tolist())
entry = {"patient":eachpatient.memid,
"capability": eachpatient.capability}
ListofPatCapability.append(entry)
JsonList = json.dumps(ListofPatCapability)
return JsonList
How can I clear the json object whenever we call api 'patient_cap'?
ListofPatCapability keeps its value between calls because you declared it as a global, so you are seeing it grow because all of your results for each call are appended to it.
Does it really need to be global? Do other parts of the program need to use it?
If not, take it out of the global section and just initialize it to be an empty list.
Right now, I have a Django application with an import feature which accepts a .zip file, reads out the csv files and formats them to JSON and then inserts them into the database. The JSON file with all the data is put into temp_dir and is called data.json.
Unfortunatly, the insertion is done like so:
Building.objects.all().delete()
call_command('loaddata', os.path.join(temp_dir, 'data.json'))
My problem is that all the data is deleted then re-added. I need to instead find a way to update and add data and not delete the data.
I've been looking at other Django commands but I can't seem to find out that would allow me to insert the data and update/add records. I'm hoping that there is a easy way to do this without modifying a whole lot.
If you loop through your data you could use get_or_create(), this will return the object if it exist and create it if it doesn't:
obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)})
Django and Python newbie here. Ok, so I want to make a webpage where the user can enter a number between 1 and 10. Then, I want to display an image corresponding to that number. Each number is associated with an image filename, and these 10 pairs are stored in a list in a .txt file.
One way to retrieve the appropriate filename is to create a NumToImage model, which has an integer field and a string field, and store all 10 NumToImage objects in the SQL database. I could then retrieve the filename for any query number. However, this does not seem like such a great solution for storing a simple .txt file which I know is not going to change.
So, what is the way to do this in Python, without using a database? I am used to C++, where I would create an array of strings, one for each of the numbers, and load these from the .txt file when the application starts. This vector would then lie within a static object such that I can access it from anywhere in my application.
How can a similar thing be done in Python? I don't know how to instantiate a Python object and then enable it to be accessible from other Python scripts. The only way I can think of doing this is to pass the object instance as an argument for every single function that I call, which is just silly.
What's the standard solution to this?
Thank you.
The Python way is quite similar: you run code at the module level, and create objects in the module namespace that can be imported by other modules.
In your case it might look something like this:
myimage.py
imagemap = {}
# Now read the (image_num, image_path) pairs from the
# file one line at a time and do:
# imagemap[image_num] = image_path
views.py
from myimage import imagemap
def my_view(image_num)
image_path = imagemap[image_num]
# do something with image_path
I am very new to Python and am not very familiar with the data structures in Python.
I am writing an automatic JSON parser in Python, the JSON message is read into a dictionary using Ultra-JSON:
jsonObjs = ujson.loads(data)
Now, if I try something like:
jsonObjs[param1][0][param2] it works fine
However, I need to get the path from an external source (I read it from the DB), we initially thought we'll just write in the DB:
myPath = [param1][0][param2]
and then try to access:
jsonObjs[myPath]
But after a couple of failures I realized I'm trying to access:
jsonObjs[[param1][0][param2]]
Is there a way to fix this without parsing myPath?
Many thanks for your help and advice
Store the keys in a format that preserves type information, e.g. JSON, and then use reduce() to perform recursive accesses on the structure.