在没有返回语句的情况下修改函数内部的字典

时间:2019-05-26 17:05:32

标签: python function dictionary return

我正在尝试在函数内修改字典。而且由于字典是可变的数据类型。我想知道是否需要返回语句?

例如:

def modify_dict(a_dict,a_key,a_value):
    a_dict = {a_key:a_value}

# Why wouldn't the function actually modify the dictionary? 
# Wouldn't the dictionary still be changed to sample_dict={e_key:e_value} anyways?

sample_dict = {b_key:b_value,c_key:c_value,d_key:d_value}
modify_dict(sample_dict,e_key,e_value)

4 个答案:

答案 0 :(得分:1)

您的修改字典未修改变量。它正在重新绑定它。

尝试:

def modify_dict(a_dict,a_key,a_value):
    a_dict[a_key] = a_value

不,您不需要“返回”。

答案 1 :(得分:1)

Python对象变量是引用
python中的赋值运算符不适用于值本身,而是适用于那些引用。

a = [1,2] # creates object [1,2]
b = [3,4] # creates object [3,4]

# a now holds a reference to [1,2]
# b now holds a reference to [3,4]

c = a

# c now holds a reference to [1,2] as well

c = [5,6] # creates object [5,6]

# c now holds a reference to [5,6] and forgets about the [1,2].
# This does NOT change the [1,2] object.

对您的函数调用也是如此:

def modify_dict(a_dict,a_key,a_value):
    # a_dict is a REFERENCE to whatever the argument of the function is

    a_dict = {a_key:a_value} # creates a new dict
    # a_dict now holds a reference to that NEW dict and forgets what it
    # was previously referencing.
    # This does not influence the object that was given as an argument

我认为这里要理解的关键概念是函数内部的参数是对对象的引用,而不是对对象本身的引用。

要实际更改a_dict,您需要直接访问它而不是分配给它,例如:

def modify_dict(a_dict,a_key,a_value):
    a_dict[a_key] = a_value

答案 2 :(得分:0)

在函数内部重新分配a_dict时,实际上是在创建一个新字典,该字典的名称与函数范围之外的字典的名称相同。如果您更新字典,则更改将在功能范围之外可见,但是您将重新分配名称。

答案 3 :(得分:0)

虽然您可以在适当位置修改字典,但是您正在将堆栈变量a_dict分配给新字典,这与更改字典中的值不同。您想要更多类似的东西:

test = {'k1': 'v1', 'k2': 'v2'}
def changes_dict(d, k, new_v):
    d[k] = new_v

changes_dict(test, 'k1', 'changed')
test['k1']
# 'changed'