update a list element using an element in another list

Rhodri James rhodri at kynesim.co.uk
Tue Jan 31 06:49:20 EST 2017

On 31/01/17 11:28, Daiyue Weng wrote:
> Hi, I am trying to update a list of dictionaries using another list of
> dictionaries correspondingly. In that, for example,
> #  the list of dicts that need to be updated
> dicts_1 = [{'dict_1': '1'}, {'dict_2': '2'}, {'dict_3': '3'}]
> # dict used to update dicts_1
> update_dicts = [{'dict_1': '1_1'}, {'dict_2': '1_2'}, {'dict_3': '1_3'}]
> so that after updating,
> dicts_1 = [{'dict_1': '1_1'}, {'dict_2': '1_2'}, {'dict_3': '1_3'}]
> what's the best way to the updates?
> This is actually coming from when I tried to create a list of entities
> (dictionaries), then updating the entities using another list dictionaries
> using google.cloud.datastore.
> entities = [Entity(self.client.key(kind, entity_id)) for entity_id in
> entity_ids]
> # update entities using update_dicts
> for j in range(len(entities)):
> for i in range(len(update_dicts)):
> if j == i:
> entities[j].update(update_dicts[i])
> I am wondering is there a brief way to do this.

This all relies on the lists being in the same order and the same 
length, which is probably an unwise assumption, but it's what your code 

for entity, update_dict in zip(entities, update_dicts):

range(len(something)) is usually a warning sign (code smell, if you 
prefer) that you aren't thinking in Python.  If you really need the list 
index for some nefarious purpose, enumerate(something) is probably still 
a better bet.

Rhodri James *-* Kynesim Ltd

More information about the Python-list mailing list