Is there something similar to list comprehension in dict?

Stefan Behnel stefan_ml at behnel.de
Fri Nov 20 03:24:31 EST 2009


Peng Yu, 20.11.2009 04:18:
> I'm wondering if there is something similar to list comprehension for
> dict (please see the example code below).

A list comprehension is an expression that produces a list, e.g.

    [ i**2 for i in range(10) ]

Your example below uses a slice assignment.


> def fun(d):#Is there a way similar to list comprehension to change the
> argument d so that d is changed?
>   d=dict(three=3)
> [...]
> def fun3(L):# argument L is changed
>   L[:]=[1, 2, 3]

You can use  d.update(...)

It accepts both another dict as well as a generator expression that
produces item tuples, e.g.

    d.update( (i, i**2) for i in range(10) )

Does that help?

Stefan



More information about the Python-list mailing list