List of Dictionaries

Jason Orendorff jason at jorendorff.com
Thu Mar 7 21:52:04 EST 2002


Lenny Self wrote:
> When I add the first dictionary element to the list all is well.  When
> I add the second element to the list both the first and second element
> reference the second dictionary that was added.

Probably you are doing something like this:

  mylist = []
  d = {}

  d['name'] = 'Jason'
  d['address'] = '123 Test Drive'
  mylist.append(d)

  d['name'] = 'Yakko'
  d['address'] = None
  mylist.append(d)

Here I'm adding the same dictionary to the list twice,
so the list contains two references to the same dictionary.
You can use the id() function to tell if two dictionaries
are exactly identical.

  >>> print mylist
  [{'name': 'Yakko', 'address': None}, {'name': 'Yakko', 'address': None}]
  >>> print d
  {'name': 'Yakko', 'address': None}
  >>> print id(mylist[0])
  8302792
  >>> print id(mylist[1])
  8302792
  >>> print id(d)
  8302792

As you can see, mylist[0], mylist[1], and d are all actually the
same dictionary.  They don't just have the same values; they're
really the same object.  One dictionary data structure exists
in memory, shared by all three references.

This is called "aliasing".  It means you have to create a new dictionary
every time you want... er... a new dictionary.  :)  Thus:

  d0 = {'name': 'Jason', 'address': '123 Test Drive'}  # create new dict
  mylist.append(d0)

  d1 = {'name': 'Yakko', 'address': None}  # create another new dict
  mylist.append(d1)

Every time you write {}, a new dictionary is created.

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list