Pass arguments to a notebook as a list

Use a JSON file to temporarily store arguments that you want to use in your notebook.

Written by pallavi.gowdar

Last published at: October 29th, 2022

There is no direct way to pass arguments to a notebook as a dictionary or list.

You can work around this limitation by serializing your list as a JSON file and then passing it as one argument.

After passing the JSON file to the notebook, you can parse it with json.loads().

Instructions

Define the argument list and convert it to a JSON file.

  1. Start by defining your argument list.
    args = {'arg_1': 'a', 'arg_2': 'b', 'arg_3': 'c', 'arg_4': 'd', 'arg_5': 'e'}
  2. Declare the arguments as a dictionary. 
  3. Use json.dumps() to convert the dictionary to JSON.
  4. Write the converted JSON to a file.
    %python
    
    import json
    
    args = {"arg_1": "a", "arg_2": "b", "arg_3": "c", "arg_4": "d", "arg_5": "e"}
    
    file = open("arguments.txt", "w")
    file.write(json.dumps(args))  
    file.close() 
    
    print("Argument file is created.")

 
Once the argument file is created, you can open it inside a notebook and use the arguments.

  1. Open the JSON file that contains the arguments.
  2. Read the contents.
  3. Use json.loads() to convert the JSON back into a dictionary. 
  4. Now the arguments are available for use inside the notebook. 
    %python
    
    import json
    
    file = open("arguments.txt", "r")
    data = file.read()
    file.close()
    
    args = json.loads(data)
    print(args)


You can use this example code as a base for your own argument lists.