Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python dict imported from file in another python file

I've the same issue as asked by the OP in How to import or include data structures (e.g. a dict) into a Python file from a separate file. However for some reason i'm unable to get it working.

My setup is as follows:

file1.py:

TMP_DATA_FILE = {'a':'val1', 'b':'val2'}

file2.py:

from file1 import TMP_DATA_FILE

var = 'a'
print(TMP_DATA_FILE[var])

When i do this and run the script from cmd line, it says string indices must be integers.

When i do type(TMP_DATA_FILE), i get class 'str'. I tried to convert this to dict to be able to use dict operations, but couldn't get it working.

If i do print(TMP_DATA_FILE.get(var)), since i'm developing using PyCharm, it lists dict operations like get(), keys(), items(), fromkeys() etc, however when i run the program from command line it says 'str' object has no attributes 'get'.

When i do print(TMP_DATA_FILE) it just lists 'val1'. It doesn't list 'a', 'b', 'val2'.

However the same script when run from PyCharm works without any issues. It's just when i run the script from command line as a separate interpreter process it gives those errors.

I'm not sure if it's PyCharm that's causing the errors or if i'm doing anything wrong.

Originally i had only one key:value in the dict variable and it worked, when i added new key:value pair that's when it started giving those errors.

I've also tried using ast.literal_eval & eval, neither of them worked. Not sure where i'm going wrong.

Any help would be highly appreciated.

Thanks.

like image 259
Murali Avatar asked Jun 17 '15 14:06

Murali


People also ask

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

Can you import functions from another Python file?

To use the functions written in one file inside another file include the import line, from filename import function_name . Note that although the file name must contain a . py extension, . py is not used as part of the filename during import.


1 Answers

There are two ways you can access variable TMP_DATA_FILE in file file1.py:

import file1
var = 'a'
print(file1.TMP_DATA_FILE[var])

or:

from file1 import TMP_DATA_FILE
var = 'a'
print(TMP_DATA_FILE[var])

In both cases, file1.py must be in a directory contained in the python search path, or in the same directory as the file importing it.

Check this answer about the python search path.

like image 163
fferri Avatar answered Nov 14 '22 23:11

fferri