Jagdev Singh
Jagdev Singh

Reputation: 895

dictionary reading from module


I have following module root_file.py. This file contains number of blocks like.

Name = {
'1':'a'
'2':'b'
'3':'c'
}

In other file I am using

f1= __import__('root_file')

Now the requirement is that I have to read values a,b,c at runtime using variables like for reading a

id=1
app=Name
print f1[app][id]

but getting error that

TypeError: unsubscriptable object

Upvotes: 0

Views: 2317

Answers (2)

masterpiga
masterpiga

Reputation: 868

Uh, well, if I understand what you are trying to do:

In root_file.py

Name = {
 '1':'a', #note the commas here!
 '2':'b', #and here
 '3':'c', #the last one is optional
}

Then, in the other file:

import root_file as mymodule
mydict = getattr(mymodule, "Name")
# "Name" could be very well be stored in a variable
# now mydict eqauls Name from root_file
# and you can access its properties, e.g.
mydict['2'] == 'b' # is a True statement

Upvotes: 1

Shekhar
Shekhar

Reputation: 7245

How about

import root_file as f1

id = 1
app = 'Name'
print getattr(f1, app)[id] # or f1.Name[id]

Upvotes: 2

Related Questions