[Tutor] python dictionary
Alan Gauld
alan.gauld at btinternet.com
Tue Apr 14 20:14:44 CEST 2009
"sudhanshu gautam" <sudhanshu9252 at gmail.com> wrote
> and setdefault used to set the value is side the dictionary if it does
> not
> lies inside the dictionary.
>
> so why we use setdefault I think in place of setdefault first we should
> convert that dictionary in the list and now we can add new value then
> again
> convert it in dictionary
You probably could convert it to a list, append a tuple and then convert
the list back to a dictionary. But why would you want to do that when
setdefault is so much easier?
Also the conversions between list and dictionary would take a lot of
time and computer power for a big dictionary
For example I tried
>>> L = [(n,n) for n in range(1000000)]
>>> d = dict(L)
>>> d2 = [(k,v) for k,v in d.items()]
>>> d.setdefault(-5,-5)
- producing the dict from the list took about half a second
- producing the list from the dict took over 3 seconds and
used over 50% of my CPU...
- using setdefault() was effectively instantaneous.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list