Dict Help

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Jul 17 09:06:45 EDT 2007


On Tue, 17 Jul 2007 10:57:29 +0100, Robert Rawlins - Think Blue wrote:

> Morning Gabriel,
> 
> I'm looking for a little more advice on this dictionary/list to
> defaultdict/set conversion that we were talking about, there were a few
> things I was looking to clarify. Firstly, what is the difference between a
> standard dict and a default dict? Is it purely a performance issue? 


>From an interactive prompt, execute the following lines:

help(dict)
import collections
help(collections.defaultdict)

A defaultdict is just like a dict except that it calls a function
(specified at init time) whenever a missing key is found. Compare:


>>> d = collections.defaultdict(lambda: 42) # new empty defaultdict
>>> d
defaultdict(<function <lambda> at 0xb7eb4ed4>, {})
>>> d[0] # key is missing
42
>>> d
defaultdict(<function <lambda> at 0xb7eb4ed4>, {0: 42})



>>> d = {} # new empty dict
>>> d.setdefault(0, 42)
42
>>> d
{0: 42}



> This dict is likely to grow pretty large 

What is "pretty large" to you or me is not necessarily large to the
computer. How many keys are you thinking it will have?


> and is read/written on a very
> regular basis so the better performing one is going to work best for me.

Python dicts are extremely efficient hash tables. They perform extremely
well and are heavily optimized.



> Also, am I still able to iterate over a set in the same way I can a list?

Why don't you try it for yourself?

for x in set([1, 2, 3]):
    print x



> Here is an example of my add function at the moment, how can that be
> converted to a defaultdict/set instead of the dict/list approach?
> 
> 	self.History = {}
> 
> 	def addHistory(self, address, media):
> 		if address not in self.History:
> 			self.History[address] = []
> 
> 		self.History[address].append(media)


def addHistory(self, address, media):
    self.history.setdefault(address, []).append(media)



-- 
Steven




More information about the Python-list mailing list