1

Brief description of code:

The main code first makes a blank dictionary, which is passed on to my function. The function tallies how many of each number and updates the dictionary which is then returned. However when the function executes, it overwrites the input 'blank_dictionary' to be the same as the dictionary it returns ('new_dictionary'). Why does this happen? I want the 'dictionary' in the main code to remain blank throughout so that it can be reused.

def index_list(lst, blank_dictionary):
    new_dictionary = blank_dictionary
    for i in lst:
        new_dictionary[i] += 1
    return new_dictionary

number = 1
maximum = 3
numbers = range(1,maximum+1)

dictionary = {}
for i in numbers:
    dictionary[i] = 0

print ('original blank dictionary', dictionary)
new_dictionary = index_list([3,3,3],dictionary)
print ('new dictionary which indexed the list', new_dictionary)
print ('should still be blank, but isnt', dictionary)

Outputs:

original blank dictionary {1: 0, 2: 0, 3: 0}
new dictionary which indexed the list {1: 0, 2: 0, 3: 3}
should still be blank, but isnt {1: 0, 2: 0, 3: 3}

Thanks very much

Nishalc
  • 33
  • 3

2 Answers2

3

You are setting new_dictionary to the reference to blank_dictionary. Change the line to new_dictionary = dict(blank_dictionary) and you will be fine. Using the dict() constructor function will make a new new_dictionary and so blank_dictionary will not be modified.

You might want to investigate the defaultdict in the collections module. If you only need to count the number of times each element appears, consider collections.counter.

PurpleDiane
  • 1,693
  • 1
  • 12
  • 15
  • Ah I see, so it is like a pointer in C if dict() isn't used? Thanks very much this was driving me nuts. – Nishalc Apr 23 '17 at 07:27
1

This behavior is not limited to dicts. In Python, any time you pass a mutable object to a function, the function operates on the original object, not a copy. This is not true for immutable objects like tuples and strings.

However in this case there is no reason to pass a blank dictionary to the function in the first place. The function can create a new dictionary and return it.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80