0

Will appending to a list in python a dictionary that already exists in the list change the item or appended at the end?

For example,

I have this in the same run of a loop (this script fills my db with movies)

movie = {'id': 102, 'name': 'The Dark Knight', 'release_date': 0} 
movies.append(movie)

Then I update my movie entry with a value for release_date, like so; (with the same run of the loop)

movie = {'id': 102, 'name': 'The Dark Knight', 'release_date': '2018-08-30'} 
movies.append(movie)

Will it update the past entry or append a new one at the end there?

2
  • 1
    It will add a new dictionary to the end of the list (testing the code in IDLE shows this). Commented Aug 30, 2018 at 5:10
  • read and understand this: nedbatchelder.com/text/names.html Commented Aug 30, 2018 at 5:36

3 Answers 3

1

Yes, It will.

Might I suggest checking the list for the current movie and then if said movie is found, removing it from the list and then appending the new dictionary.

Sign up to request clarification or add additional context in comments.

Comments

0

The code will add a new dictionary to the end of movies:

From IDLE

>>> movies = []
>>> movie = {'id': 102, 'name': 'The Dark Knight', 'release_date': 0}
>>> movies.append(movie)
>>> print(movies)
[{'id': 102, 'name': 'The Dark Knight', 'release_date': 0}]
>>> movie = {'id': 102, 'name': 'The Dark Knight', 'release_date': '2018-08-30'}
>>> movies.append(movie)
>>> print(movies)
[{'id': 102, 'name': 'The Dark Knight', 'release_date': 0}, {'id': 102, 'name': 'The Dark Knight', 'release_date': '2018-08-30'}]

Comments

0

Appends at end. Python 2.7.12

>>> movie = {'id':102,'name':'The Dark Knight','release_date':0}
>>> movies = []
>>> movies.append(movie)
>>> print(movies)
[{'release_date': 0, 'id': 102, 'name': 'The Dark Knight'}]
>>> movie = {'id':102,'name':'The Dark Knight','release_date':'2018-08-30'}
>>> movies.append(movie)
>>> print(movies)
[{'release_date': 0, 'id': 102, 'name': 'The Dark Knight'}, {'release_date': '2018-08-30', 'id': 102, 'name': 'The Dark Knight'}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.