如何在函数中创建字典?

gus*_*a10 0 python dictionary function

我想在我的函数中创建一个字典,但我不能.我找到的唯一可能的解决方案是在函数外部和调用之前创建字典的名称.

argentina = {}
def get_dic(file,phone):
    for line in file.readlines():
        if (line[0] == '#'):
            names = line.rstrip().strip()
            phone[names] = ''
        else:
            phone[names] = phone[names] + line.rstrip().strip()

get_dic(open(sys.argv[1],'r'), argentina)
Run Code Online (Sandbox Code Playgroud)

get_dic(open(sys.argv[1],'r'), argentina)将打开一本名为'argentina'的字典,但我不需要argentina = {}提前创建.

iBu*_*Bug 6

只需在里面创建dict并从函数中返回它:

def get_dic(file):
    phone = {}
    names = None
    for line in file.readlines():
        if line[0] == '#':
            names = line.strip()
            phone[names] = ""
        else:
            phone[names] += line.strip()
    return phone

argentina = get_dic(open(sys.argv[1],'r'))
Run Code Online (Sandbox Code Playgroud)