Search code examples
python-3.xlistpython-module

Asking the user what list to access from a different module


I have a few lists in a separate python file. What I want to do ask the user which list they would like to get access to, and then use that list in my main py file. I am getting an error, can't find attribute 'x', x being the input variable in which the list name is stored. Any help would be appreciated.

Code

import module_name 

lst = input('Which list?') 

a = module_name.lst //getting an attribute error, no lst in module_name 

Solution

  • To access lists by a string, you need to store the lists in a dictionary.

    -- module_name.py

    lst = { 
      'a': [1,2,3,4],
      'b': [5,6,7,8]
    }
    

    -- module_main.py

    import module_name 
    
    lstname = input('Which list?')  # a
    
    xx = module_name.lst[lstname] 
    
    print(xx)  # print selected list