1

I wanted to access a dictionary created in file1.py from file2.py based on value passed in a variable. Both files in same directory.

File1.py looks like

dict_test_1 = {'a':1, 'b': 2}

dict_test_2 = {'a':11, 'b': 12}

file2.py looks like:

import file1

def fun(dict_name):

    var_a = file1.dict_name['a'] ## I wanted an equivalent of file1.dict_test_1['a'] or file.dict_test_2['a'] 

fun(deciding variable which is coming from run time) # Calling function

I need to access either of dictionary created in file1.py at run time by 'dict_name' but the problem is python actually sees 'dict_name' as it one of the dictionary defined in file1.py instead of taking value of 'dict_value' variable passed in function 'fun' and looking for corresponding dictionary.

Any solutions??

user2033758
  • 1,848
  • 3
  • 16
  • 16

2 Answers2

1

I would suggest something along these lines:

def fun(dict_name):
    selected_dict = {'dict_test_1': file1.dict_test_1,
                     'dict_test_2': file1.dict_test_2 }

    var_a = file1.selected_dict[dict_name]['a'] 
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • Although this is great if you can know for certain which dicts will exist in `file1`, it's tough to generalize that. Unfortunately this is one of those times where using `vars` or `module.__dict__` is the correct approach – Adam Smith Dec 09 '14 at 00:20
  • Yep, this would be an other way. I assumed the OP knows the dictionaries in advance. Please feel free to provide alternative way. – Marcin Dec 09 '14 at 00:23
1

If you need to access a python object by value, you've got to deal with the kludge of vars or object__dict__.

You have a string dict_name that will correspond to the name of a python object inside the module file1. If file1 was a dictionary, you'd do file1[dict_name], right? That's where __dict__ comes in.

def fun(dict_name):
    selected_dict = file1.__dict__[dict_name]
    var_a = selected_dict['a']

This is similarly written by using the vars built-in. It is better explained on this SO question

def fun(dict_name):
    selected_dict = vars(file1)[dict_name]
    var_a = selected_dict['a']
Community
  • 1
  • 1
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • Thank you @Adam Smith. That helped me. It worked out both ways (Vars and __dict__) Thanks for new lesson. – user2033758 Dec 09 '14 at 16:38
  • @user2033758 right, because `vars(some_object)` returns `some_object.__dict__` (just like `len(some_list)` returns `some_list.__len__()`) – Adam Smith Dec 09 '14 at 16:43