python修改方法内的字典

2 python dictionary

是否可以修改函数内的字典值而不将字典作为参数传递.

我不想返回字典,只是为了修改它的值.

Ash*_*ary 5

是的,你可以,字典是一个可变对象,所以它们可以在函数内修改,但它必须在你实际调用函数之前定义。

要更改指向不可变对象的全局变量的值,您必须使用该global语句。

>>> def func():
...     dic['a']+=1
...     
>>> dic = {'a':1}    #dict defined before function call
>>> func()
>>> dic
{'a': 2}
Run Code Online (Sandbox Code Playgroud)

对于不可变对象:

>>> foo = 1
>>> def func():
...     global foo
...     foo += 3   #now the global variable foo actually points to a new value 4
...     
>>> func()
>>> foo
4
Run Code Online (Sandbox Code Playgroud)

  • 我知道你的意思,但根据定义,你不能修改不可变对象。您正在做的是更改名称所指的内容。 (8认同)

T. *_*Rex 5

这是可能的,但不一定是可取的,我无法想象为什么你不想传递或返回字典,如果你只是不想返回字典,但可以通过它,你可以修改它以反映原始字典无需返回,例如:

dict = {'1':'one','2':'two'}
def foo(d):
   d['1'] = 'ONE'

print dict['1']  # prints 'one' original value
foo(dict)
print dict['1']  # prints 'ONE' ie, modification reflects in original value
                 # so no need to return it
Run Code Online (Sandbox Code Playgroud)

但是,如果由于某种原因绝对无法传递它,则可以使用全局字典,如下所示:

global dict                    # declare dictionary as global
dict = {'1':'one','2':'two'}   # give initial value to dict

def foo():

   global dict   # bind dict to the one in global scope
   dict['1'] = 'ONE'

print dict['1']  # prints 'one'
foo(dict)
print dict['1']  # prints 'ONE'
Run Code Online (Sandbox Code Playgroud)

我建议在第一个代码块中演示第一种方法,但如果绝对必要,可以随意使用第二种方法.请享用 :)