[Python-ideas] dictionary unpacking

Mathias Panzenböck grosser.meister.morti at gmx.net
Wed Apr 2 19:44:51 CEST 2008


Maybe just extend the functionality of the __getitem__ and __setitem__ methods of dicts?

 >>> class xdict(dict):
	def __getitem__(self,key):
		if type(key) in (tuple, list):
			return (dict.__getitem__(self,k) for k in key)
		else:
			return dict.__getitem__(self,key)
		
	def __setitem__(self,key,value):
		if type(key) in (tuple, list):
			for k, v in zip(key,value):
				dict.__setitem__(self,k,v)
		else:
			dict.__setitem__(self,key,value)

			
 >>> d=xdict({'foo':23,'bar':42,'egg':'spam'})
 >>> d
{'bar': 42, 'foo': 23, 'egg': 'spam'}
 >>> d["foo",]
<generator object at 0x9dbc02c>
 >>> list(d["foo",])
[23]
 >>> list(d["foo","bar"])
[23, 42]
 >>> a,b=d['foo','egg']
 >>> a,b
(23, 'spam')
 >>> d['baken','bar'] = 'tomato', 36
 >>> d
{'bar': 36, 'foo': 23, 'egg': 'spam', 'baken': 'tomato'}


Well, this would break current behaviour, so actually no. Not good.
But maybe that way (no conflict because lists are unhashable):

 >>> class xdict(dict):
	def __getitem__(self,key):
		if isinstance(key,list):
			return (dict.__getitem__(self,k) for k in key)
		else:
			return dict.__getitem__(self,key)

	def __setitem__(self,key,value):
		if isinstance(key,list):
			for k, v in zip(key,value):
				dict.__setitem__(self,k,v)
		else:
			dict.__setitem__(self,key,value)

			
 >>> d=xdict({'foo':23,'bar':42,'egg':'spam'})
 >>> list(d[["foo"]])
[23]
 >>> list(d[["foo","bar"]])
[23, 42]
 >>> a,b=d[['foo','egg']]
 >>> a,b
(23, 'spam')
 >>> d[['baken','bar']] = 'tomato', 36
 >>> d
{'bar': 36, 'foo': 23, 'egg': 'spam', 'baken': 'tomato'}


The [[ ]] looks almost like a spacial syntax. Good or bad?

	-panzi



More information about the Python-ideas mailing list