473,625 Members | 3,254 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

False and 0 in the same dictionary

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 key-value pairs for 0,
False, 1 and True.
As I have learnt, 0 and False both hash to the same value (same for 1
and True).
>>b = {0:'xyz', False:'abc'}
b
{0: 'abc'} # Am I the only one who thinks this is weird?

This obviously stems from the fact that 0 == False but 0 is not False
etc. etc.

That doesn't help my case where I need to distinguish between the two

The same issue applies in a list:

Suppose I do:
>>a = [0, 1, True, False]
a.index(False )
0

Wha??? Help.
Nov 4 '08 #1
14 3325
Prateek <su*****@gmail. comwrote:
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 key-value pairs for 0,
False, 1 and True.
How about using (x, type(x)) as the key instead of just x?

Nov 4 '08 #2
On Nov 5, 1:52*am, Duncan Booth <duncan.bo...@i nvalid.invalidw rote:
Prateek <sure...@gmail. comwrote:
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 key-value pairs for 0,
False, 1 and True.

How about using (x, type(x)) as the key instead of just x?
Yup. I thought of that. Although it seems kinda unpythonic to do so.
Especially since the dictionary is basically a cache mostly containing
strings. Adding all the memory overhead for the extra tuples seems
like a waste just for those four keys.

Is there a better way?
I also thought of using a custom __eq__ method in a custom class
which extends the dict type but decided that was even worse.

Prateek
Nov 4 '08 #3
On Nov 4, 4:21*pm, Prateek <sure...@gmail. comwrote:
On Nov 5, 1:52*am, Duncan Booth <duncan.bo...@i nvalid.invalidw rote:
Prateek <sure...@gmail. comwrote:
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 key-value pairs for 0,
False, 1 and True.
How about using (x, type(x)) as the key instead of just x?

Yup. I thought of that. Although it seems kinda unpythonic to do so.
Especially since the dictionary is basically a cache mostly containing
strings. Adding all the memory overhead for the extra tuples seems
like a waste just for those four keys.

Is there a better way?
I also thought of using a custom __eq__ *method in a custom class
which extends the dict type but decided that was even worse.

Prateek
Hmm, my original reply didn't show up.

I'm curious as to what you're trying to accomplish.

Bear in mind that I type this response not knowing your application.
While Python is not a statically typed language, 0 and False are
essentially different types (int and bool). Storing them both as keys
of a dictionary just doesn't seem like a good design.
Nov 4 '08 #4
Prateek <su*****@gmail. comwrites:
On Nov 5, 1:52*am, Duncan Booth <duncan.bo...@i nvalid.invalidw rote:
>Prateek <sure...@gmail. comwrote:
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 key-value pairs for 0,
False, 1 and True.

How about using (x, type(x)) as the key instead of just x?

Yup. I thought of that. Although it seems kinda unpythonic to do so.
Especially since the dictionary is basically a cache mostly containing
strings. Adding all the memory overhead for the extra tuples seems
like a waste just for those four keys.

Is there a better way?
I also thought of using a custom __eq__ method in a custom class
which extends the dict type but decided that was even worse.

Prateek
You could use currying on Duncan's solution :). It would
give something like this (minimal implementation) :

from collections import defaultdict

class DictByType(obje ct):
def __init__(self):
self.dicts = defaultdict(dic t)
def __setitem__(sel f, key, val):
self.dicts[type(key)][key] = val
def __getitem__(sel f, key):
return self.dicts[type(key)][key]
Then:
>>d = DictByType()
d[1]='foo'
d[True]='bar'
d[1.0] = 'foobar'
d[1], d[True], d[1.0]
('foo', 'bar', 'foobar')

If, as seems to be the case, you have many keys with few types, then the
memory overhead will be smaller. Access time might suffer though.

--
Arnaud
Nov 4 '08 #5
Prateek <su*****@gmail. comwrites:
>b = {0:'xyz', False:'abc'}
b
{0: 'abc'} # Am I the only one who thinks this is weird?
You're not the only one; I consider this a wart in Python.

False and True should be discrete values that don't compare equal with
any other value, not even ones that evaluate to boolean False or True.
>>False == []
False
>>False == {}
False
>>False == ''
False
>>False == 0
True

This is an artifact of the fact that ‘bool’ is a subclass of ‘int’,
and that ‘False’ is implemented such that it has the same hash as ‘0’:
>>isinstance(Fa lse, int)
True
>>hash(False) == hash(0)
True

The above is a legacy of the original lack of a boolean type in
Python, but it's confusing and IMO unnecessary these days. It should
be enough that they all evaluate to False in a boolean context:
>>bool([])
False
>>bool({})
False
>>bool('')
False
>>bool(0)
False

PEP 285 <URL:http://www.python.org/dev/peps/pep-0285>, that introduced
the ‘bool’ type, addresses this issue:

In an ideal world, bool might be better implemented as a
separate integer type that knows how to perform mixed-mode
arithmetic. However, inheriting bool from int eases the
implementation enormously (in part since all C code that calls
PyInt_Check() will continue to work -- this returns true for
subclasses of int). Also, I believe this is right in terms of
substitutabilit y: code that requires an int can be fed a bool
and it will behave the same as 0 or 1. Code that requires a
bool may not work when it is given an int; for example, 3 & 4
is 0, but both 3 and 4 are true when considered as truth
values.

I wonder if any of that is relevant any more.

What does backward-compatibility-is-less-important Python 3 do (I
don't have it installed)? Is there a later PEP that I've missed which
finally makes ‘bool’ a type independent from ‘int’?

--
\ “A ‘No’ uttered from deepest conviction is better and greater |
`\ than a ‘Yes’ merely uttered to please, or what is worse, to |
_o__) avoid trouble.” —Mahatma Gandhi |
Ben Finney
Nov 4 '08 #6
"Prateek" <su*****@gmail. comwrote:
>b = {0:'xyz', False:'abc'}
b
{0: 'abc'} # Am I the only one who thinks this is weird?
No. This was discussed before on this list, and that discussion
referenced (if I recall correctly) the discussion on python-dev
at the time the decision was taken.

If my name were Laura Creighton, I would now say:

"I told you so!"

Now I have to weigh my words carefully to make sure I
am not misunderstood:

You are screwed!

- Hendrik

Nov 5 '08 #7
Ben Finney:
Is there a later PEP that I've missed which
finally makes bool a type independent from int?
In a tidy language like an ObjectPascal or Java bools and integers are
different types.

In Python if bools become distinct from integers you have to rewrite
things like:
sum(el == val for el in iterable)
as:
sum(1 for el in iterable if el == val)

In the past here I have stated that boolean operators should return
only boolean values, and I believe it still. Because doing otherwise
is quite confusing.

But in practice I have seen that while being a little untidy, having
bools as subtype of int doesn't lead to much bugs, and it has few
practical advantages. So purity isn't that useful here.

Having an iterable that contains both ints and bools isn't too much
common, because while Python isn't statically typed, in practice most
of the times in most Python programs types are uniform and predictable
(that's why ShedSkin can work).

And even if you have a list that contains bools and integers mixed,
then having to tell them apart (by hashing, etc) is quite uncommon, I
think I have never had to do it in 2-3 years. So maybe is that code
that is doing something messy, so maybe is that code that has to
change and become more tidy, and not the language itself :-)

Bye,
bearophile
Nov 5 '08 #8
Prateek:
How do I make a dictionary which has distinct key-value pairs for 0,
False, 1 and True.
Why do you have to do that? What's the problem you have to solve?
Maybe (probably) there are better or more clean alternative solutions.

Bye,
bearophile
Nov 5 '08 #9
On Wed, 05 Nov 2008 04:22:32 -0800, bearophileHUGS wrote:
In Python if bools become distinct from integers you have to rewrite
things like:
sum(el == val for el in iterable)
as:
sum(1 for el in iterable if el == val)
I would expect that you can still "cast" `bool`\s to `int`\s then.
Sometimes I write it as

sum(int(el == val) for el in iterable)

just for clarity what the intent is.

Ciao,
Marc 'BlackJack' Rintsch
Nov 5 '08 #10

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

Similar topics

1
3582
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 respectively In the sample code you see that I have class Item and class Dict class Dict contains a dictionary called items. The items dictionary will contain instances of Item that are keyed off of the Item name. In __main__ I create two...
4
2512
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 want to # init a class from that dictionary. # However, I don't want to specify the # dictionary gets by hand # since it is error prone.
4
18725
by: Bradley Plett | last post by:
I have what should be a trivial problem. I am using XMLSerializer to serialize an object. It serializes boolean values as "True" and "False". I then want to use an XSLT on this XML, and I want to use one of these booleans in a test. How do I convert one of these to a boolean in a test?!? I know that I could compare it as a string to "True" or "False", but that seems extremely crude to me. The "boolean()" function (which, to me, seems...
1
9247
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 DataBinding accepts as a data source either an IList or an IListSource at System.Windows.Forms.ListControl.set_DataSource(Object value)
8
3106
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 was not at all what I expected. Ultimately I realized I don't really know how literals are treated within the interpreter. The two implementations I was looking at were: class caseFunction(object): def __init__(self):
8
13313
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 dictionaries which themselves may contain ints, None and more dictionaries. Each of the sub-dictionaries is also arbitrarily large. When pretty printing A, in the context I'm using A for, it's rather helpful to remove all key:value pairs where value...
3
2206
by: JamesB | last post by:
I have a config screen in my app that updates a dictionary<key,value>. I want to store a copy of this before going into the config screen so if the user wants to cancel all their changes I can simply set the working copies to be the backup. So, in my code, before the config screen is shown, I do this: Dictionary<string, myClassTempDic = MainDic;
3
4178
by: wildThought | last post by:
If I have an object that contains a generic dictionary inside of it, how do I get access to its properties such as count?
1
2271
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) Dictionary<string, Dictionary<string, string>> d = new Dictionary<string, Dictionary<string, string>>(); Now I am using GetDictionaryType Function where I an sending a dictionary object. In GetDictionaryType() I want to find out which dictionary...
0
8189
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8635
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7184
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 projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4089
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4193
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2621
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1500
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.