7

Is it possible to modify values for a dictionary inside a function without passing the dictionary as a parameter.

I would like not to return a dictionary, but only to modify its values.

  • 2
    Why can't you pass the dictionary as a parameter? Relying upon closing over a variable in the global namespace is bad in 99% of cases. – aestrivex May 28 '13 at 17:38

2 Answers2

15

That's possible, but not necessarily advisable, i can't imagine why you wouldn't like to pass or return the dictionary, if you merely don't want to return the dictionary, but could pass it, you can modify it to reflect in the original dictionary without having to return it, for example:

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

However, if you absolutely cannot pass it for whatever reason, you can use a global dictionary as follows:

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'

I'd recommend the first method demonstrated in the first code block, but feel free to use the second if absolutely necessary. Enjoy :)

SamAko
  • 3,485
  • 7
  • 41
  • 77
6

Yes you can, dictionary is an mutable object so they can be modified within functions, but it must be defined before you actually call the function.

To change the value of global variable pointing to an immutable object you must use the global statement.

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

For immutable objects:

>>> foo = 1
>>> def func():
...     global foo
...     foo += 3   #now the global variable foo actually points to a new value 4
...     
>>> func()
>>> foo
4
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 11
    I know what you mean, but you can't modify immutable objects, by definition. What you're doing is changing what the name refers to. – Daniel Roseman May 28 '13 at 17:16