【问题标题】:python returning empty dictionary from modulepython从模块返回空字典
【发布时间】:2015-11-25 14:29:49
【问题描述】:

我正在尝试从模块返回字典,但无论在 Windows 7 上的 Python2.7 上如何,字典都返回为空。例如:

test_dict.py

def get_dict():
    dictiom = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    print dictiom['Name']
    return dictiom['Name']

if __name__ == '__main__':
    get_dict()

get_dict.py

import test_dict

dict_test = test_dict.get_dict()
print dict_test

独立运行test_dict.py,打印语句返回

Zara

从 get_dict.py 打印调用 dict

{}

这是一个简化的示例,但对于我尝试过的其他测试也是如此。

更新以更改我的示例错误。

好的,这是我实际代码的问题部分

搜索.py

from Bio import Entrez


def search(query):

    Entrez.email = 'me@example.com'
    handle = Entrez.esearch(db='pubmed',
                        sort='relevance',
                        retmax='50',
                        retmode='xml',
                        term=query)
    results = Entrez.read(handle)
    return results

main.py

import Search

query = 'cancer'
results = Search.search(query)
print(results)

results 是一个空字典,但无法找出原因。但是单独运行 Search.py​​ 是可行的。

【问题讨论】:

  • dict() 已经是用于创建字典的内置函数...不要为函数/变量使用内置名称
  • 好点,我在把这个例子放在一起时忘记了这一点。我的真实代码没有使用 dict 示例。

标签: python dictionary


【解决方案1】:

给你的函数起一个不同的名字!
dict 是一个内置函数。

test_dict.py

def get_dict():
    dictiom = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
    return dictiom #I think you want to return the whole dict?

if __name__ == '__main__':
    print get_dict() # print the dict as a test 

那么你可以这样做

ma​​in.py

import test_dict

dict_test = test_dict.get_dict()
print dict_test

【讨论】:

  • 我认为应该是“dict_test = test_dict.get_dict()”
【解决方案2】:

如果你使用

import test_dict

那你必须打电话

test_dict.dict()

如果你使用

from test_dict import dict

那你就可以打电话了

dict()

编辑:

你可以使用

from test_dict import dict as my_dict

然后打电话

my_dict()

防止与原dict()冲突

【讨论】:

  • 除此之外,我认为不建议将函数命名为dict(),因为它与python的内置函数冲突。
  • 这太糟糕了。它鼓励为自己制作的函数使用内置函数名称。永远不要这样做
  • @furas“防止与原始dict() 冲突的正确方法是根本不命名任何dict - 想象一下你从from test_dict import * 得到的混乱
猜你喜欢
  • 1970-01-01
  • 2013-11-30
  • 2020-05-22
  • 1970-01-01
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 2010-09-26
  • 1970-01-01
相关资源
最近更新 更多