0

example.py This is a python script, which has a multi-level dictionary.

test_dict = {'path': '/home/user/user_name',
 'device1': {'IP': '10.10.10.10',
          'password': 'pwd1',
          'username': 'user1',
          'name':'USER_DEFINED'},
 'device2': {'IP': '11.11.11.11',
          'password': 'pwd2',
          'username': 'user2',
          'name':'USER_DEFINED_TEST'}
}

I've written a separate python script to update the dictionary present in 'example.py'. Currently, I could able to handle a first level dictionary [Ex: path and it's value], via option parser. python example.py --key path --value /home/user/user_name. SO, now in order to handle updating the multilevel dictionary values. How do i optimize it ? Could you please help me ?

    Working :
    file_abs_path = "C://Test_Folder//example.py"
    module = imp.load_source('test_dict', file_abs_path)
    f_dict = module.test_dict
    if f_key != "":
       for key, value in f_dict.items():
         if key == f_key:
            f_dict[f_key] = f_value

parser.add_option("-k", "--key", dest="key",default="",help="")

parser.add_option("-v", "--value", dest="value",default="",help="")
f_key = options.key 
f_value = options.value

if at all to update the device1 name & device2 name or it could be device1 settings name. How would i optimize it ?

Jackie
  • 129
  • 17
  • I would load the dictionary dynamically from a file in `example.py` and write to this file. Have you looked at something like [cPickle](https://pymotw.com/2/pickle/)? – martianwars Nov 18 '16 at 07:08
  • This is a nice example of an x-y problem :-). You wonder how to update a dict in a Python file. But if it has to be updated in should not lie in a Python file but in a *data* file. json module for example is great at dealing with dictionaries, while having a format easily editable *by hand* (with a simple text editor). – Serge Ballesta Nov 18 '16 at 07:52

1 Answers1

0

It doesn't seem very necessary to directly update example.py's dictionary in this case. I would adopt a slightly different approach of reading data from a file using cPickle.

In your example.py file, use this snippet to read the data -

import cPickle
with open(r"data.pk", "rb") as input_file:
  cPickle.load(d, input_file) 

To write to this cPickle file (from another script),

import cPickle
d = {
  'a': {'b': 5, 'c': 6},
  'd': {'e': 7, 'f': 8}
}
# Add some logic to dynamically update d
with open(r"data.pk", "wb") as output_file:
  cPickle.load(d, output_file) 
martianwars
  • 6,380
  • 5
  • 35
  • 44