list.append not working?

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Mon Jul 9 18:21:37 CEST 2007


Hardy a écrit :
> On 5 Jul., 18:07, infidel <saint.infi... at gmail.com> wrote:
>> On Jul 5, 8:58 am, Hardy <hhart... at gmail.com> wrote:
>>
>>
>>
>>> I experience a problem with append(). This is a part of my code:
>>>         for entity in temp:
>>>             md['module']= entity.addr.get('module')
>>>             md['id']=entity.addr.get('id')
>>>             md['type']=entity.addr.get('type')
>>>             #print md
>>>             mbusentities.append(md)
>>>             #print mbusentities
>>> I want something like: [{'module': 'home', 'id': 123, 'type': 'core'},
>>> {'module': 'work', 'id': 456, 'type': 'core'}]
>>> md is always correct, BUT:mbusentities is wrong. Length of
>>> mbusentities is same of temp, so it appended everything. BUT:
>>> mbusentities only shows the values of the last append: [{'module':
>>> 'work', 'id': 456, 'type': 'core'}, {'module': 'work', 'id': 456,
>>> 'type': 'core'}]
>>> What's wrong?
>> You're reusing the same "md" dictionary over and over, appending the
>> same object to the list each time.  So what you have is a list of
>> references to the same dictionary.  You need to set md = {} first
>> thing each iteration.
> 
> Thanks, that was my mistake, should take a break, getting code-blind :D
> 

append = mbusentities.append
for entity in temp:
   get = entity.addr.get
   append(dict((k, get(k)) for k in ('module', 'id', 'type')))



More information about the Python-list mailing list