Is there something similar to list comprehension in dict?

Dave Angel davea at ieee.org
Fri Nov 20 06:45:27 EST 2009


Peng Yu wrote:
> I'm wondering if there is something similar to list comprehension for
> dict (please see the example code below).
>
>
> d = dict(one=1, two=2)
> print d
>
> 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)
>
> fun(d)
> print d
>
> def fun1(d):
>   d['one']=-1
>
> fun1(d)
> print d
>
>
> L = [1, 2]
> print L
>
> def fun2(L):#this doesn't have any effect on the argument L
>   L=[]
>
> fun2(L)
> print L#[1, 2]
>
> def fun3(L):# argument L is changed
>   L[:]=[1, 2, 3]
>
> fun3(L)
> print L#[1, 2, 3]
>
>   
You confused me by calling it a list comprehension.  All you're using in 
fun3() is a slice.  Using a slice, you can give a new set of values to 
an existing list.

For a dictionary, it's just a bit trickier.  You need two steps in the 
most general case.

def fun4(d):
       d.clear()          #clear out existing entries
        d.update(new_dict)          #copy in new key:val pairs from a 
different dictionary

This function will modify the caller's dictionary, completely replacing 
the contents.

DaveA



More information about the Python-list mailing list