using setDefault

gzeljko gzeljko at sezampro.yu
Tue Aug 14 16:25:01 CEST 2001

From: Mark Robinson <m.1.robinson at>

> I am updating some of my older code to use the setdefault dictionary 
> method. Where I had code saying:
> if dict.has_key(x):
> dict[x].append(y)
> else:
> dict[x] = [y]
> now I smile and say:
> dict.setdefault(x, []).append(y)
> very nice. I am wondering if this approach can be adapted to a situation 
> where you are merging two dictionaries. So currently I have a situation 
> where for example:
> for x in a.keys():
> if b.has_key(x):
> for item in a[x]: 
> try:
> b[x].index(item)
> except ValueError:
> b[x].append(item)
> else:
> b[x] = a[x]
> I can't see how that can be rewritten, but I have a feeling there is 
> prossibly a better way

I'd write that:

for x in a.keys():
  item = b.setdefault(x,[])
  item += [y for y in a[x] if y not in item]

Difference from orginal: 
  copying from a when not b.has_key(x)
  missing check for uniquenes in a[x]


More information about the Python-list mailing list