473,398 Members | 2,403 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

use cases for a defaultdict

Steven Bethard wrote:
Agreed. I really hope that Python 3.0 applies Raymond Hettinger's
suggestion "Improved default value logic for Dictionaries" from
http://wiki.python.org/moin/Python3%2e0Suggestions

This would allow you to make the setdefault() call only once, instead
of on every lookup:

class meh(dict):
def __init__(self, *args, **kwargs):
super(meh, self).__init__(*args, **kwargs)
self.setdefault(function=meh)
Steve Holden wrote: In fact, why not go one better and also add a "default" keyword
parameter to dict()?
Steven Bethard wrote: It's not backwards compatible:
>>> dict(default=4) {'default': 4}
Steve Holden wrote: Nyargle. Thanks, you're quite right, of course: I was focussing on the
list-of-pairs argument style when I wrote that. So the best we could
do is provide a subtype, defaultdict(default, *args, *kw).
Steven D'Aprano wrote: I vote to leave dict just as it is, and add a subclass, either in a
module or as a built in (I'm not fussed either way) for
dicts-with-defaults.


Yeah, I like that idea too. That's a lot of Steven's agreeing on this
-- do we realy need agreement from people with other names too? ;)

I do think defaultdict() is probably the right way to go, though I'm not
certain about the signature -- it needs to support value-based defaults
(e.g. 0) and function based defaults (e.g. a new list each time).
Perhaps we need to introduce two new collections objects,
defaultvaluedict and defaultfunctiondict:
class defaultdict(dict): .... def __init__(self, default, *args, **kwargs):
.... super(defaultdict, self).__init__(*args, **kwargs)
.... self._default = default
.... def __repr__(self):
.... type_name = type(self).__name__
.... super_str = super(defaultdict, self).__repr__()
.... return '%s(%r, %s)' % (type_name, self._default, super_str)
.... class defaultvaluedict(defaultdict): .... def __getitem__(self, key):
.... if key not in self:
.... self[key] = self._default
.... return super(defaultvaluedict, self).__getitem__(key)
.... class defaultfunctiondict(defaultdict): .... def __getitem__(self, key):
.... if key not in self:
.... self[key] = self._default()
.... return super(defaultfunctiondict, self).__getitem__(key)
.... counts = defaultvaluedict(0)
counts['Steve'] += 1
counts['Steve'] += 1
counts['Steven'] += 1
counts defaultvaluedict(0, {'Steve': 2, 'Steven': 1}) groups = defaultfunctiondict(list)
groups['Steve'].append('Holden')
groups['Steve'].append('Bethard')
groups['Steven'].append("D'Aprano")
groups

defaultfunctiondict(<type 'list'>, {'Steve': ['Holden', 'Bethard'],
'Steven': ["D'Aprano"]})

I didn't override of get() or setdefault(), which means they don't use
the default associated with the dict. I think this is right because the
only time you'd use get() or setdefault() with a defaultdict is if you
wanted to override the default normally associated with it.

The question, I guess, is whether or not there are enough use cases to
merit introducing these types into the collections module. Some of my
use cases:

* Counting numbers of items, using defaultvaluedict(0). Currently, I
support this by having a counts() function in my dicttools module:

def counts(iterable, key=None):
result = {}
for item in iterable:
# apply key function if necessary
if key is None:
k = item
else:
k = key(item)
# increment key's count
try:
result[k] += 1
except KeyError:
result[k] = 1
return result

Raymond Hettinger has also proposed a bag_ recipe for similar purposes.

... _bag: http://aspn.activestate.com/ASPN/Coo.../Recipe/259174

* Grouping items into lists, using defaultfunctiondict(list).
Currently, I support this by having a groupby() function in my dicttools
module:

def groupby(iterable, key=None, value=None):
result = {}
for item in iterable:
# apply key function if necessary
if key is None:
k = item
else:
k = key(item)
# apply value function if necessary
if value is None:
v = item
else:
v = value(item)
# append value to key's list
try:
result[k].append(v)
except KeyError:
result[k] = [v]
return result

Note that for both of my use cases, the appropriate defaultdict() could
take the try/except (equivalent to a setdefault() call) out of my code.
It's nice, but not a huge gain -- I definitely can't drop my code
completely...

Do others have compelling use-cases for a defaultdict-like class?

STeVe
Jan 18 '06 #1
0 1074

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Bryan Parkoff | last post by:
C++ programmers and I tried to experience by writing 65536 switch cases. It is too large for Windows XP and other operating system to handle. It looks like that JMP Table obtains 256K bytes for...
65
by: He Shiming | last post by:
Hi, I just wrote a function that has over 200 "cases" wrapped in a "switch" statement. I'm wondering if there are performance issues in such implementation. Do I need to optimize it some way? ...
30
by: Raymond Hettinger | last post by:
Proposal -------- I am gathering data to evaluate a request for an alternate version of itertools.izip() with a None fill-in feature like that for the built-in map() function: >>> map(None,...
3
by: bearophileHUGS | last post by:
This post sums some things I have written in another Python newsgroup. More than 40% of the times I use defaultdict like this, to count things: .... defaultdict(<type 'int'>, {'a': 5, 'r': 2,...
3
by: Raymond Hettinger | last post by:
FWIW, here are three ways of writing constant functions for collections.defaultdict(): d = defaultdict(int) # slowest way; works only for zero d = defaultdict(lambda: 0) # faster way;...
2
by: tutufan | last post by:
It seems like x = defaultdict(defaultdict(list)) should do the obvious, but it doesn't. This seems to work y = defaultdict(lambda: defaultdict(list)) though is a bit uglier.
2
by: metaperl.com | last post by:
I'm reading http://norvig.com/spell-correct.html and do not understand the expression listed in the subject which is part of this function: def train(features): model =...
3
by: fizilla | last post by:
Hello all! I have the following weird problem and since I am new to Python I somehow cannot figure out an elegant solution. The problem reduces to the following question: How to pickle a...
7
by: Matthew Wilson | last post by:
I used defaultdict.fromkeys to make a new defaultdict instance, but I was surprised by behavior: defaultdict(None, {'y': <type 'list'>, 'x': <type 'list'>}) <type 'list'> ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.