如何在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
我该怎么做?
答案 0 :(得分:4)
你需要将dict复制到tempdict。
def foobar(d):
temp = d.copy()
# your logic goes here
return temp
copy
制作dict的浅表副本(即复制其值,但不复制其值的值)。
% 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}
>>>