如何将新的字典名称作为参数传递给Python中的函数?

时间:2013-05-16 17:45:05

标签: python

我是一名新程序员,并且在将新字典名称作为参数传递给函数方面存在问题 我正在尝试创建一个函数,该函数将从网页下拉数据并为主机名创建字典键和整行数据的值。有多个页面具有主机名的通用性作为键值,我最终将它们连接在一起。

首先,我创建一个名为control的列表,用作我正在搜索的所有主机的密钥文件。然后,我将值webpagedelimiterdictionary name传递给函数 这样做时,似乎字典的名称没有传递给函数。

#open key file
f = open("./hosts2", "r")
control = []
for line in f:
    line = line.rstrip('\n')
    line = line.lower()
    m = re.match('(^[\w\d]+)', line)
    control.append(m.group())
# Close key file
f.close()

def osinfo(url, delimiter, name=None):
    ufile = urllib2.urlopen(url)
    ufile.readline()
    name = {}
    for lines in ufile.readlines():
        lines = lines.rstrip("\n")
        fields = lines.split(delimiter)
        m = re.match(r'(?i)(^[a-z0-9|\.|-]+)', fields[1].lower())
        hostname = m.group()
        if hostname in control:
            name[hostname] = lines
    print "The length of osdata inside the function:", len(name)

osdata = {}
osinfo(‘http://blahblah.com/test.scsv’, ';', name='osdata')
print "The length of osdata outside the function", len(osdata)

输出如下:

$./test.py
The length of osdata inside the function: 11
The length of osdata outside the function: 0

该功能似乎没有提取关键字。

这是否由于范围?

2 个答案:

答案 0 :(得分:3)

您应该传递对象name='osdata'

,而不是传递字符串name=osdata

并且不要在函数内重新定义它:name = {},否则你将失去对原始对象的引用。

>>> def func(name=None):
    name ={}         #redefine the variable , now reference to original object is lost
    return id(name)
... 
>> dic={}
>>> id(dic),func(dic)   #different IDs
(165644460, 165645684)

必读:How do I pass a variable by reference?

答案 1 :(得分:1)

您传递name参数,然后在使用name之前在您的函数内使用{}初始化name:好像没有name arg是过去了。

def osinfo(url, delimiter, name=None):
    ufile = urllib2.urlopen(url)
    ufile.readline()
    name = {}                               # you define name here as empty dict
        for lines in ufile.readlines():
            lines = lines.rstrip("\n")
            fields = lines.split(delimiter)
            m = re.match(r'(?i)(^[a-z0-9|\.|-]+)', fields[1].lower())
            hostname = m.group()
            if hostname in control:
                name[hostname] = lines
        print "The length of osdata inside the function:", len(name)

然后是两条评论

  • 如果你想修改字典,把它作为参数传递,而不是它的名字

  • 你是对的一点:在Python中,如果作为参数传递的对象是可变的,那么生活在外部作用域中并作为参数传递的变量可以被函数修改(就好像它通过引用传递的那样) ,更准确地说,对象的引用是按值传递的,see here