Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Solution

Tomas Skacel
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tomas Skacel
Python Development Techdegree Graduate 8,994 Points

Original data is being changed even though a copy was made

from data import data

def data_cleaner(arg):
    for dictionary in arg:
        namesplit = dictionary['name'].split(' ')
        dictionary['first name'] = namesplit[0]
        dictionary['last name'] = namesplit[1]
        del(dictionary['name'])
        if dictionary['admin'] == 'False':
            dictionary['admin'] = False
        elif dictionary['admin'] == 'True':
            dictionary['admin'] = True
        dictionary['id'] = int(dictionary['id'])    
    return arg    

data_copy = data.copy()
cleaned_data = data_cleaner(data_copy)

Hello! This was my initial attempt at this challenge. It does what the challenge asked for, but I did notice something strange. The reason I made a copy of data was to preserve a copy of the original. However, if I print data after running my code, data has been changed and is the same as cleaned_data, even though data was never passed into the function. Why is this happening? Is there any way to make this work?

1 Answer

Rachel Johnson
STAFF
Rachel Johnson
Treehouse Teacher

Hey Tomas Skacel , thanks for your question!

The reason that the original is showing changes is because a shallow copy() was used to copy the data. If you want to preserve the original, what we call a "deep" copy, you'll want to use .deepcopy()

From the Python docs:

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

I hope this helps!