using setDefault

Mark Robinson m.1.robinson at herts.ac.uk
Tue Aug 14 06:21:59 EDT 2001


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

blobby




More information about the Python-list mailing list