0

I'm new to dictionaries and have found the following to be very confusing.

resume = [{'name': 'New', 'value1': 'dfgdf'}, {'name': 'garry', 'value1': 'hhhhhh'}]
current = resume[0]
current['name'] = '24/7 link was not requested...'
print(resume)

Returns:

[{'name': '24/7 link was not requested...', 'value1': 'dfgdf'}, {'name': 'garry', 'value1': 'hhhhhh'}]

Why is this happening when a permanent/continuous link between resume and current was not requested? ...... and how can I change this so that current['name'] will update to the new/requested string value and not resume.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Rhys
  • 4,926
  • 14
  • 41
  • 64
  • 2
    But current *is* the first dictionary in resume. – Daniel Roseman Sep 29 '18 at 19:56
  • yes it is, but when i change the values in `current` with `current['name']` ... the value in `resume` should not change. I did not ask for that. – Rhys Sep 29 '18 at 19:58
  • 1
    Is the issue that you don't want to modify the first element in `resume`? If so, you can do `current = resume[0].copy()` to get a copy of the first element instead. More on that [here](https://stackoverflow.com/questions/23852480/assigning-value-in-python-dict-copy-vs-reference) – jDo Sep 29 '18 at 20:00
  • 1
    I would also suggest reading about it in here: https://realpython.com/copying-python-objects/ – Adelina Sep 29 '18 at 20:01
  • 2
    @Rhys yes, you **did** ask for that. Please read https://nedbatchelder.com/text/names.html And this has nothing to do with dictionaries, this is how assignment works for *all objects in Python* – juanpa.arrivillaga Sep 29 '18 at 20:03

1 Answers1

3

Try changing

current = resume[0]

to

current = resume[0].copy()

This should create a new dictionary object.

Sebiancoder
  • 104
  • 2
  • 10