Dict Help

pruebauno at latinmail.com pruebauno at latinmail.com
Tue Jul 17 20:29:19 CEST 2007

On Jul 17, 5:57 am, "Robert Rawlins - Think Blue"
<robert.rawl... at thinkbluemedia.co.uk> 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?
> This dict is likely to grow pretty large and is read/written on a very
> regular basis so the better performing one is going to work best for me.
> Also, am I still able to iterate over a set in the same way I can a list?
> 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)
> Thanks Gabriel,
> Rob
1. defaultdict just sets a dictionary entry to a default if the key
does not exist. In other words if you replace the first line with:

self.History=defaultdict(list) #replace list by set if you want

you can get rid of:

if address not in self.History: self.History[address]=[]

because that then happens automatically. Otherwise it works exactly
like a regular dictionary.

2. You can iterate over a set the same way you iterate over a list.

3. Change the following lines:

line 5 self.History[address] = set() #instead of [] (list)
line 7 self.History[address].add(media) #set uses add instead of

More information about the Python-list mailing list