update a list element using an element in another list

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Tue Jan 31 06:53:13 EST 2017


Daiyue Weng writes:

> 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 restored the indentation.]

> I am wondering is there a brief way to do this.

A straightforward algorithmic improvement:

for j in range(len(entities)):
    entities[j].update(update_dicts[j])

The real thing:

for e, u in zip(entities, update_dicts):
    e.update(u)

A thing between those:

for j, e in enumerate(entities):
    e.update(update_dicts[j])

(By symmetry, you could enumerate update_dicts instead.)

It pays to learn zip and enumerate.



More information about the Python-list mailing list