2010-08-30 62 views
1

如何创建一个Python字典传递给一个函数,以便它看起来像这样:如何修改本地的字典,以不影响全局变量在python

def foobar(dict): 
    dict = tempdict # I want tempdict to not point to dict, but to be a different dict 
    #logic that modifies tempdict 
    return tempdict 

我如何做这个?

+2

'字典'不是字典的好名字;它影响了内建的'dict'。 – 2010-08-31 00:22:25

+0

好的。我没有打算使用它,但我会牢记它。感谢您的领导! – 2010-08-31 01:12:55

回答

4

你需要复制字典到tempdict。

def foobar(d): 
    temp = d.copy() 
    # your logic goes here 
    return temp 

copy使得字典的浅表副本(即复制其值,但不是其值值)。

% python 
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> d = {'x': 17, 'y': 23} 
>>> t = d.copy() 
>>> t 
{'y': 23, 'x': 17} 
>>> t['x'] = 93 
>>> t 
{'y': 23, 'x': 93} 
>>> d 
{'y': 23, 'x': 17} 
>>>