473,394 Members | 1,640 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,394 software developers and data experts.

dictionary wart

Does python have a way of defining a dictionary default?
I think not, but are there any plans to incorporate it?

Intuitively I would imagine that

a={}
a.set_default(my_default)

would do this -ie. a[my_new_key] should now return the the default
value my_default instead of creating an exception. This would be
similar to how it is done in other languages, eg. Ruby:

a={}
a.default=value

But surprisingly, in python set_default is a dictionary method used
for looking up a key...

Jesper
Jul 18 '05 #1
6 1650
jo****@mail2world.com (Jesper Olsen) writes:
Does python have a way of defining a dictionary default?
I think not, but are there any plans to incorporate it?

Intuitively I would imagine that

a={}
a.set_default(my_default)

would do this -ie. a[my_new_key] should now return the the default
value my_default instead of creating an exception.


No, instead of a[my_new_key] use a.get(my_new_key, my_default).
That does what you want.
Jul 18 '05 #2
On 18 Mar 2004 04:41:38 -0800, Jesper Olsen wrote:
Does python have a way of defining a dictionary default?
I think not, but are there any plans to incorporate it?

But surprisingly, in python set_default is a dictionary method used
for looking up a key...


(Probably you mean setdefault(), since there's no set_default attribute
in any default Python object.)

A dict, by design, has a defined set of keys, like all mapping types.
Your "dictionary default" would change a dictionary so that it
effectively had an infinite set of keys.

<http://www.python.org/doc/current/lib/typesmapping.html>

It sounds like you want an iterator, rather than a dict.

<http://www.python.org/doc/current/lib/typeiter.html>

But without knowing the problem you're trying to solve, we can only
guess at the solution.

--
\ "I got a postcard from my best friend, it was a satellite |
`\ picture of the entire Earth. On the back he wrote, 'Wish you |
_o__) were here'." -- Steven Wright |
Ben Finney <http://bignose.squidly.org/>
Jul 18 '05 #3
Paul Rubin wrote:
jo****@mail2world.com (Jesper Olsen) writes:
Does python have a way of defining a dictionary default?
I think not, but are there any plans to incorporate it?

Intuitively I would imagine that

a={}
a.set_default(my_default)

would do this -ie. a[my_new_key] should now return the the default
value my_default instead of creating an exception.

No, instead of a[my_new_key] use a.get(my_new_key, my_default).
That does what you want.


Unfortunately not - get() is different, because you can not assign to it.
For instance in a dictionary which is mapping strings to integers (or
lists), I would like to do

a[my_key]+=5

expressing that with get() would be awkward.

Jesper
Jul 18 '05 #4
On Thu, 18 Mar 2004 13:46:19 GMT, Jesper <jo****@mail2world.com>
wrote:
Paul Rubin wrote:
jo****@mail2world.com (Jesper Olsen) writes:
Does python have a way of defining a dictionary default?
I think not, but are there any plans to incorporate it?

Intuitively I would imagine that

a={}
a.set_default(my_default)

would do this -ie. a[my_new_key] should now return the the default
value my_default instead of creating an exception.

No, instead of a[my_new_key] use a.get(my_new_key, my_default).
That does what you want.


Unfortunately not - get() is different, because you can not assign to it.
For instance in a dictionary which is mapping strings to integers (or
lists), I would like to do

a[my_key]+=5

expressing that with get() would be awkward.

Jesper


You can however subclass dict to create something that *behaves* like
a dictionary, but for unknown keys returns a default :

Regards,

Fuzzy

http://www.voidspace.org.uk/atlantib...thonutils.html

e.g. (untested - but should work)
class defaultDict(dict):
"""A dictionary that returns a default for non-existent keys.
Won't work for methods like pop unless you also define them as
well."""
def __init__(self, default):
dict.__init__(self)
self.default = default

def __getitem__(self, item):
if self.has_key(item):
return dict.__getitem__(self, key)
else:
return self.default

if __name__ == '__main__':
a = defaultDict(3)
a['test'] = 4
print a['test']
print a['fish']


---
Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong
Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera

http://www.voidspace.org.uk
Where Headspace Meets Cyberspace
Cyberpunk and Science Resource Site
Exploring the worlds of Psychology, Spirituality, Science and Computing
--
http://www.fuchsiashockz.co.uk
http://groups.yahoo.com/group/void-shockz
http://www.learnlandrover.com
Jul 18 '05 #5
On Thu, 18 Mar 2004 15:06:48 +0000, Fuzzyman <mi*****@foord.net>
wrote:
On Thu, 18 Mar 2004 13:46:19 GMT, Jesper <jo****@mail2world.com>
wrote:
Paul Rubin wrote:
jo****@mail2world.com (Jesper Olsen) writes:

Does python have a way of defining a dictionary default?
I think not, but are there any plans to incorporate it?

Intuitively I would imagine that

a={}
a.set_default(my_default)

would do this -ie. a[my_new_key] should now return the the default
value my_default instead of creating an exception.
No, instead of a[my_new_key] use a.get(my_new_key, my_default).
That does what you want.
Unfortunately not - get() is different, because you can not assign to it.
For instance in a dictionary which is mapping strings to integers (or
lists), I would like to do

a[my_key]+=5

expressing that with get() would be awkward.

Jesper


You can however subclass dict to create something that *behaves* like
a dictionary, but for unknown keys returns a default :

Regards,

Fuzzy

http://www.voidspace.org.uk/atlantib...thonutils.html

e.g. (untested - but should work)
class defaultDict(dict):
"""A dictionary that returns a default for non-existent keys.
Won't work for methods like pop unless you also define them as
well."""
def __init__(self, default):
dict.__init__(self)
self.default = default

def __getitem__(self, item):
if self.has_key(item):
return dict.__getitem__(self, key)
else:
return self.default


Oops - that would be (and I see that someone else already suggested
this anyway )...

return dict.__getitem__(self, item)

if __name__ == '__main__':
a = defaultDict(3)
a['test'] = 4
print a['test']
print a['fish']


---
Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong
Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera

http://www.voidspace.org.uk
Where Headspace Meets Cyberspace
Cyberpunk and Science Resource Site
Exploring the worlds of Psychology, Spirituality, Science and Computing


---
Everyone has talent. What is rare is the courage to follow talent to the dark place where it leads. -Erica Jong
Ambition is a poor excuse for not having sense enough to be lazy. -Milan Kundera

http://www.voidspace.org.uk
Where Headspace Meets Cyberspace
Cyberpunk and Science Resource Site
Exploring the worlds of Psychology, Spirituality, Science and Computing
--
http://www.fuchsiashockz.co.uk
http://groups.yahoo.com/group/void-shockz
http://www.learnlandrover.com
Jul 18 '05 #6

Jesper> For instance in a dictionary which is mapping strings to
Jesper> integers (or lists), I would like to do

Jesper> a[my_key]+=5

Jesper> expressing that with get() would be awkward.

Though not *terribly* awkward:

a[my_key] = a.get(my_key, 0) + 5

I agree it's a bit clumsy, but I think it's the best you can do if you don't
want to subclass dict (I don't really like {}.setdefault()):

class ddict(dict):
def __init__(self, default=None, init=True):
self.default = default
self.init = init

def __getitem__(self, key):
if key in self:
return self.get(key)
else:
if self.init:
self[key] = self.default
return self.default

d = ddict(default="Jesper", init=False)
print "abc" in d
print d["abc"]
d = ddict(default=0)
d["abc"] += 5
print d["abc"]

I suspect there's more to it than I've implemented, but that should get you
pointed in the right direction.

Skip

Jul 18 '05 #7

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

Similar topics

1
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148...
4
by: brianobush | last post by:
# # My problem is that I want to create a # class, but the variables aren't known # all at once. So, I use a dictionary to # store the values in temporarily. # Then when I have a complete set, I...
125
by: Raymond Hettinger | last post by:
I would like to get everyone's thoughts on two new dictionary methods: def count(self, value, qty=1): try: self += qty except KeyError: self = qty def appendlist(self, key, *values): try:
1
by: john wright | last post by:
I have a dictionary oject I created and I want to bind a listbox to it. I am including the code for the dictionary object. Here is the error I am getting: "System.Exception: Complex...
7
by: Paul Rubin | last post by:
I tried to code the Sieve of Erastosthenes with generators: def sieve_all(n = 100): # yield all primes up to n stream = iter(xrange(2, n)) while True: p = stream.next() yield p # filter out...
8
by: akameswaran | last post by:
I wrote up a quick little set of tests, I was acutally comparing ways of doing "case" behavior just to get some performance information. Now two of my test cases had almost identical results which...
8
by: Brian L. Troutwine | last post by:
I've got a problem that I can't seem to get my head around and hoped somebody might help me out a bit: I've got a dictionary, A, that is arbitarily large and may contains ints, None and more...
14
by: Prateek | last post by:
I've been using Python for a while (4 years) so I feel like a moron writing this post because I think I should know the answer to this question: How do I make a dictionary which has distinct...
1
by: sachin2 | last post by:
I am using 3 types of dictionaries. 1) Dictionary<string, string > d = new Dictionary<string, string>(); 2) Dictionary<string, List<string>> d = new Dictionary<string, List<string>>(); 3)...
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: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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...

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.