Python Forum
Unexpected behavior appending to a List of Dictionaries
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unexpected behavior appending to a List of Dictionaries
#2
You need to read about mutable and immutable objects in Python.

Dictionaries are mutable objects, so they could be changed in-place:

single_alien = {'color': 'grey', 'points': 8, 'speed': 'ultraslow'}

print(id(single_alien)) # print unique identifier of the object single_alien
# assume, that returned by `id` value is 12345

single_alien['color'] = 'green'
single_alien['points'] =  5
single_alien['speed'] = 'slow'

print(id(single_alien)) # lets print id again, after changes... 
# it is 12345! # So, the object was changed in-place, this is mutability...
aliens.append(single_alien)
 
single_alien['color'] = 'blue'
single_alien['points'] =  6
single_alien['speed'] = 'medium'

print(id(single_alien))
# it is still...  12345!
aliens.append(single_alien)
So, each time you appending single_alien to aliens, Python just duplicates references to the object single_alien;

for alien in aliens:
 print(id(alien))
 # will give the same values 
Each time you assigning a new dictionary to the single_alien,
internally, a new python object is created. You can check it with id.
ids will be different...

single_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
print(id(single_alien))
# eg. 123456
aliens.append(single_alien)

single_alien = {'color': 'blue', 'points': 6, 'speed': 'medium'}
print(id(single_alien))
# eg. 123234  123234!=123456, i.e. another object!
aliens.append(single_alien)
Reply


Messages In This Thread
RE: Unexpected behavior appending to a List of Dictionaries - by scidam - Apr-03-2018, 12:39 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a list of dictionaries by the only dictionary key Calab 1 504 Oct-27-2023, 03:03 PM
Last Post: buran
  Access list of dictionaries britesc 4 1,092 Jul-26-2023, 05:00 AM
Last Post: Pedroski55
  behavior list of lists roym 5 2,116 Jul-04-2021, 04:43 PM
Last Post: roym
  function that returns a list of dictionaries nostradamus64 2 1,765 May-06-2021, 09:58 PM
Last Post: nostradamus64
  Time.sleep: stop appending item to the list if time is early quest 0 1,885 Apr-13-2021, 11:44 AM
Last Post: quest
  Reading and appending list MrSwiss 1 1,738 Mar-01-2021, 09:01 AM
Last Post: Serafim
  convert List with dictionaries to a single dictionary iamaghost 3 2,880 Jan-22-2021, 03:56 PM
Last Post: iamaghost
  Appending list Trouble Big Time Milfredo 7 3,140 Oct-01-2020, 02:59 AM
Last Post: Milfredo
  Creating a list of dictionaries while iterating pythonnewbie138 6 3,313 Sep-27-2020, 08:23 PM
Last Post: pythonnewbie138
  Appending to list of list in For loop nico_mnbl 2 2,376 Sep-25-2020, 04:09 PM
Last Post: nico_mnbl

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020