0

My scenario is:

I have a dictionary imported from a python file. After some calculations, I updated that dictionary.

from python_file import variable as vrbl

vrbl['new_key001'] = value001
vrbl['new_key002] = value002

What I want:

I want to update this change to that file as well. I have searched many questions but none of them meets my scenario. Below is the content of my python file.

python_file.py

variable = {key1: value1, key2: value2, key3: value3}

after updates python_file.py would look like:

variable = {key1: value1, key2: value2, key3: value3, new_key001: value001, new_key002: value002}

Thanks in advance!

fakhir hanif
  • 663
  • 1
  • 8
  • 17
  • 2
    You want the changes to be **written back to the file?** Are you sure you want to be producing Python source code programmatically?! Sounds like a bad idea. To store data, use a data file like JSON, or perhaps a pickled file. Not Python source code. – deceze Feb 02 '17 at 14:07
  • you are right, Actually I am not familiar with pickles that is why I choose this. Python dictionary search is very fast. can you explain how I can achieve the same through pickle file. – fakhir hanif Feb 02 '17 at 14:14
  • I want to import data from that pickle file as a dictionary and do some check, if any key matches to some variable then add a new key to that dictionary and save back to that file. – fakhir hanif Feb 02 '17 at 14:16
  • The duplicate illustrates very simply how to use pickle. You already know how to add keys, so no additional clarification should be needed there. – deceze Feb 02 '17 at 14:17
  • But right now I want to fix it by using dictionaries. – fakhir hanif Feb 02 '17 at 14:18
  • I do not need pickles right now. – fakhir hanif Feb 02 '17 at 14:19
  • To be quite frank, what you want is *insane*. Nobody should do that. Use pickle! – deceze Feb 02 '17 at 14:23
  • 1
    I am switched to pickles. Changed my requirement as you suggest @deceze. :) – fakhir hanif Feb 03 '17 at 06:52

0 Answers0