enhancing dictionary update method and the dict type constructor

Alexis Layton alexis.layton at post.harvard.edu
Sat Nov 17 13:37:30 EST 2001


This message proposes two minor enhancements. Since I've missed the
feature freeze for Python 2.2, this would be for the next version.

The first enhacement improves the definition of the dictionary "update"
method, the second enhancement broadens the dictionary type constructor.

In Python 2.2, the new dictionary type factory function "dict"
(previously known as "dictionary" in 2.2b1) takes either a mapping
object or a sequence of key, value pairs as its argument.

I would like to propose that the dictionary method "update" be broadened
to take a similar argument type.  In addition, I believe it would be
generally useful if the sequence form allowed singleton sequences to
represent keys that should be omitted from the dictionary, thus:

	d = {'a': 1, 'b': 2}
	d.update([('a',), ('b', 0), ('c', 3)])
	print d
	{'c': 3, 'b': 0}

I propose that non-existant keys specified in such an update sequence be
silently ignored.

Given such an expansion of update, it seems to me the more useful
constructor for dictionaries would be something more akin to:

	def dict(*mss):
		d = { }
		for map_or_sequence in mss:
			d.update(map_or_sequence)
		return d

This permits several useful idioms, such as the common case in
environment binding where a dictionary represents a symbol table and one
must construct a subsidiary dictionary in which one binding has changed:

	d2 = dict(d, ('v', 3))

It also permits the "union" of two or more dictionaries: dict(d1, d2).

ASIDE: what is the proper term for this, since keys in d2 can override
those in d1?

Finally, for years I've had a little utility function (called "dict" by
the way) which constructs dictionaries in which all the keys are
identifiers anyway using the keyword syntax:

	def dict(**kw): return kw

The reason is mostly to pre-load certain stupid little look-up tables
using a more convenient syntax: dict(a=1, b=2, c=3), etc.

The type constructor could also have a **kw behavior which is the final
update into the new dictionary, as if dict was defined to be:

	def dict(*mss, **kw):
		d = { }
		for ms in mss:
			d.update(ms)
		d.update(kw)
		return d


Alexis Layton
alexis.layton at post.harvard.edu




More information about the Python-list mailing list