从变量中分配Python字典值

时间:2015-01-15 01:46:22

标签: python

我有这个例程:

def _get_files_download_list(self, proj):
    tmp = {}

    # get the global file download list
    global_files = self.config['projects']['global']['server_group']['global']['file_download']

    for k in proj['server_group'].keys():
        # create the array for each server group
        # add the global stuff to each server group
        tmp_keys = global_files
        try:
            if 'file_download' in proj['server_group'][k]:
                # loop the server groups and add the file_download to that array
                for key in proj['server_group'][k]['file_download']:
                    # this way if something overrides the global, so be it, but the global is added to everything
                    tmp_keys[key] = proj['server_group'][k]['file_download'][key]
        except KeyError as e:
            pass

        if len(tmp_keys) > 0:
            tmp[k] = tmp_keys
    return tmp

问题出在例程结束时,不同的tmp[k]值都具有相同的值。我怀疑问题与python将变量链接到内存中的字典的方式有关。即思考python在内存中指定一个指向对象位置的指针,而不是在tmp_keys = global_files行上创建对象的新实例。如果我是正确的,那么语法是什么来创建对象的新实例,而不仅仅是更新现有实例。

1 个答案:

答案 0 :(得分:0)

怎么样:

import copy
tmp_keys = copy.copy(global_files)

根据global_files中的数据类型,它只能传入引用。