简体   繁体   English

如何从 python 文件中访问字典(使用 python)

[英]How can i access a dictionary from a python file (using python)

I have this file named "names.py"我有这个文件名为“names.py”

names = {}

names['males']=[
  "Bob",
  "Will",
  "John"
]
names['female']=[
  "Anna",
  "Lindsay",
  "Nicole",
]

i also have this other .py file named "income.py"我还有另一个名为“income.py”的.py文件

exec(open("names.py").read())
print(names["males"])

But this isn't working.但这行不通。 It sais there is no "names" variable.它说没有“名称”变量。 Does anyone know how to do it?有谁知道该怎么做? It must be 2 differently files.它必须是 2 个不同的文件。

Filelord alludes to how you might do this with an import statement. Filelord 暗示了您可以如何使用 import 语句来做到这一点。 Picking up on his comment, here is one possible way when "names.py" is in the same folder/directory.根据他的评论,当“names.py”位于同一文件夹/目录中时,这是一种可能的方式。

import names

print(names.names['males'])

When I executed this program, this is what printed on my terminal.当我执行这个程序时,这就是我终端上打印的内容。

['Bob', 'Will', 'John']

Hope that clarifies things.希望能澄清事情。

Regards.问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM