2015-12-21 53 views
1

我想在python中使用函数创建字典和存储信息。
我写下面的代码。这本词典的名字是什么?

def qwer(num, dictname): 
    tmp_inte = 0 
    dictname = {} 
    print dictname 
    while tmp_inte <= num: 
     dictname[str(tmp_inte)] = tmp_inte 
     tmp_inte += 1 

如果我导入此并使用它像qwer(10, "equip"),什么是新创建的字典的名字吗?

如果它的名字是'dictname',我应该怎么做才能让它按照我的意愿工作?

+2

对象实际上不具有*名称。你应该把这个字典“归还”。 – user2357112

+0

从函数返回dictname将其用作字典供进一步使用 – virendrao

+0

字典没有名称。列表或集或任何其他对象都不会。您可以将它们分配给变量,并通过这些变量引用它们,但任何这样的变量名称都严格独立于它们引用的对象。 –

回答

3

该字典被命名为dictname,但仅在函数qwer的范围内,因为那是它被声明为局部变量的地方。 dictname = {}行会影响您作为参数传递给函数的值dictname。也许你想要做的是返回从功能的词典和该值在调用者分配到dictname

def qwer(num): 
    d = {} 
    tmp_inte = 0 
    while tmp_inte <= num: 
     d[str(tmp_inte)] = tmp_inte 
     tmp_inte += 1 
    return d 


dictname = qwer(10) 

ETA:

顺便说一句,写你的功能越来越Python的方式将是:

def qwer(num): 
    d = {} 
    for i in range(num+1): 
     d[str(i)] = i 
    return d 

更是如此(对于Python 3.X):

def qwer(num): 
    return dict([(str(i), i) for i in range(num+1)]) 

或Python 2.x的:

def qwer(num): 
    return dict([(str(i), i) for i in xrange(num+1)]) 
4

如果dictname是您在作为参数传递一个字符串,该引用只会被覆盖,当你做dictname = {}。该新创建的字典的引用是dictname。但是,一旦函数结束,它就会立即抛弃。你应该return吧。然后,你必须保存的参考,当你把它叫做:

def qwer(num): 
    tmp_create = 0 
    dictname = {} 
    print dictname 
    while tmp_create <= num: 
     dictname[str(tmp_create)] = tmp_create 
     tmp_create += 1 
    return dictname 

equip = qwer(10) 

现在你有{'0':0, '1':1,... '10':10}字典保存到一个名为equip参考。