Is it reasonable to use None as a dictionary key in Python?
None seems to work as a dictionary key, but I am wondering if that will just lead to trouble later. For example, this works:
>>> x={'a':1, 'b':2, None:3}
>>> x
{'a': 1, None: 3, 'b': 2}
>>> x[None]
3
The actual data I am working with is educational standards. Every standard is associated with a content area. Some standards are also associated with content subareas. I would like to make a nested dictionary of the form {contentArea:{contentSubArea:[standards]}}
. Some of those contentSubArea keys would be None.
In particular, I am wondering if this will lead to confusion if I look for a key that does not exist at some point, or something unanticipated like that.
python dictionary key
add a comment |
None seems to work as a dictionary key, but I am wondering if that will just lead to trouble later. For example, this works:
>>> x={'a':1, 'b':2, None:3}
>>> x
{'a': 1, None: 3, 'b': 2}
>>> x[None]
3
The actual data I am working with is educational standards. Every standard is associated with a content area. Some standards are also associated with content subareas. I would like to make a nested dictionary of the form {contentArea:{contentSubArea:[standards]}}
. Some of those contentSubArea keys would be None.
In particular, I am wondering if this will lead to confusion if I look for a key that does not exist at some point, or something unanticipated like that.
python dictionary key
2
What does cause trouble is usingNaN
as a key. It's deceptive, because it's hashable, but doesn't compare equal to itself. That is:float('nan') == float('nan')
returnsFalse
, as it should, on two Python implementations I've tried. If you use it as a key in a dictionary, it won't raise an exception, and using it as an index will work if and only if it is the sameNaN
object (has the sameid(..)
) — though this might be implementation-dependent. So it might work as expected for a while, and then fail. None of these troubles affectNone
, even just because there is only oneNone
.
– Evgeni Sergeev
May 24 '16 at 4:43
add a comment |
None seems to work as a dictionary key, but I am wondering if that will just lead to trouble later. For example, this works:
>>> x={'a':1, 'b':2, None:3}
>>> x
{'a': 1, None: 3, 'b': 2}
>>> x[None]
3
The actual data I am working with is educational standards. Every standard is associated with a content area. Some standards are also associated with content subareas. I would like to make a nested dictionary of the form {contentArea:{contentSubArea:[standards]}}
. Some of those contentSubArea keys would be None.
In particular, I am wondering if this will lead to confusion if I look for a key that does not exist at some point, or something unanticipated like that.
python dictionary key
None seems to work as a dictionary key, but I am wondering if that will just lead to trouble later. For example, this works:
>>> x={'a':1, 'b':2, None:3}
>>> x
{'a': 1, None: 3, 'b': 2}
>>> x[None]
3
The actual data I am working with is educational standards. Every standard is associated with a content area. Some standards are also associated with content subareas. I would like to make a nested dictionary of the form {contentArea:{contentSubArea:[standards]}}
. Some of those contentSubArea keys would be None.
In particular, I am wondering if this will lead to confusion if I look for a key that does not exist at some point, or something unanticipated like that.
python dictionary key
python dictionary key
edited Nov 23 '18 at 9:10
Martin Thoma
42.5k57301524
42.5k57301524
asked Aug 11 '11 at 17:09
japhyrjaphyr
69011122
69011122
2
What does cause trouble is usingNaN
as a key. It's deceptive, because it's hashable, but doesn't compare equal to itself. That is:float('nan') == float('nan')
returnsFalse
, as it should, on two Python implementations I've tried. If you use it as a key in a dictionary, it won't raise an exception, and using it as an index will work if and only if it is the sameNaN
object (has the sameid(..)
) — though this might be implementation-dependent. So it might work as expected for a while, and then fail. None of these troubles affectNone
, even just because there is only oneNone
.
– Evgeni Sergeev
May 24 '16 at 4:43
add a comment |
2
What does cause trouble is usingNaN
as a key. It's deceptive, because it's hashable, but doesn't compare equal to itself. That is:float('nan') == float('nan')
returnsFalse
, as it should, on two Python implementations I've tried. If you use it as a key in a dictionary, it won't raise an exception, and using it as an index will work if and only if it is the sameNaN
object (has the sameid(..)
) — though this might be implementation-dependent. So it might work as expected for a while, and then fail. None of these troubles affectNone
, even just because there is only oneNone
.
– Evgeni Sergeev
May 24 '16 at 4:43
2
2
What does cause trouble is using
NaN
as a key. It's deceptive, because it's hashable, but doesn't compare equal to itself. That is: float('nan') == float('nan')
returns False
, as it should, on two Python implementations I've tried. If you use it as a key in a dictionary, it won't raise an exception, and using it as an index will work if and only if it is the same NaN
object (has the same id(..)
) — though this might be implementation-dependent. So it might work as expected for a while, and then fail. None of these troubles affect None
, even just because there is only one None
.– Evgeni Sergeev
May 24 '16 at 4:43
What does cause trouble is using
NaN
as a key. It's deceptive, because it's hashable, but doesn't compare equal to itself. That is: float('nan') == float('nan')
returns False
, as it should, on two Python implementations I've tried. If you use it as a key in a dictionary, it won't raise an exception, and using it as an index will work if and only if it is the same NaN
object (has the same id(..)
) — though this might be implementation-dependent. So it might work as expected for a while, and then fail. None of these troubles affect None
, even just because there is only one None
.– Evgeni Sergeev
May 24 '16 at 4:43
add a comment |
6 Answers
6
active
oldest
votes
Any hashable value is a valid Python Dictionary Key. For this reason, None is a perfectly valid candidate. There's no confusion when looking for non-existent keys - the presence of None as a key would not affect the ability to check for whether another key was present. Ex:
>>> d = {1: 'a', 2: 'b', None: 'c'}
>>> 1 in d
True
>>> 5 in d
False
>>> None in d
True
There's no conflict, and you can test for it just like normal. It shouldn't cause you a problem. The standard 1-to-1 Key-Value association still exists, so you can't have multiple things in the None key, but using None as a key shouldn't pose a problem by itself.
add a comment |
None
is not special in any particular way, it's just another python value. Its only distinction is that it happens to be the return value of a function that doesn't specify any other return value, and it also happens to be a common default value (the default arg of dict.get()
, for instance).
You won't cause any run-time conflicts using such a key, but you should ask yourself if that's really a meaningful value to use for a key. It's often more helpful, from the point of view of reading code and understanding what it does, to use a designated instance for special values. Something like:
NoSubContent = SubContentArea(name=None)
{"contentArea":
{NoSubContent:[standards],
SubContentArea(name="Fruits"): ['apples', 'bananas']}}
1
Doesn't this approach just move the use of None down a level? I was thinking it might be better to only set values that have meanings. Then None represents empty data, and errors indicate problems with data (assuming proper validation and requirements such as allowing null or requiring not null).
– japhyr
Aug 11 '11 at 17:23
1
Like I said, there's nothing really special aboutNone
, and I don't think I'd hesitate to use it as a key in a dict if it were obvious what that must mean for that dict; but if the dict is reasonably heterogeneous, or visible across a large part of the program; adding some meaning to the type of the key could be helpful. It's not so much a question of avoiding theNone
value as picking a unity value with a type that explains itself better thanNone
can.
– SingleNegationElimination
Aug 11 '11 at 17:31
I accepted gddc's answer, but upvoted this answer as well. Using None is working so far, but I can see the advantages to creating a specific key to represent None in a specific context.
– japhyr
Aug 11 '11 at 22:10
I don't think you want to 'use a key to representNone
' that's absurd, just useNone
if you need to representNone
. On the other hand, you might useNone
to represent a degenerate case of your particular application domain, or that could be confusing so you use a designated instance of another class to represent that degenerate case.
– SingleNegationElimination
Aug 12 '11 at 13:03
IsNone
in any possible way similar to 'void' data type present in C/C++.
– darth_coder
May 31 '15 at 6:01
add a comment |
You want trouble? here we go:
>>> json.loads(json.dumps({None:None}))
{u'null': None}
So yea, better stay away from json if you do use None
as a key. You can patch this by custom (de/)serializer, but I would advise against use of None
as a key in the first place.
add a comment |
It seems to me, the larger, later problem is this. If your process is creating pairs and some pairs have a "None" key, then it will overwrite all the previous None pairs. Your dictionary will silently throw out values because you had duplicate None keys. No?
I was going to use None as a key, thought "I'll just see what stackoverflow has to say about it" This persuaded me not to
– Dan
Mar 22 '15 at 11:27
1
What if you had a "5" key. Wouldn't that get silently overwritten too? Why is the None object special in that way?
– Mad Physicist
Dec 31 '15 at 13:24
@MadPhysicist - It's not. Dictionaries are always 1-to-1 key-to-value containers. Reassigning any key will replace whatever was in the key previously.
– g.d.d.c
Feb 26 '16 at 15:33
1
@g.d.d.c. I agree. My point is then thatNone
is just as valid a key as5
. There's no good reason not to use it if it is convenient to do so.
– Mad Physicist
Feb 26 '16 at 16:01
add a comment |
Funny though, even this works :
d = {None: 'None'}
In [10]: None in d
Out[10]: True
add a comment |
No. It will only cause headaches in the future. Use a dummy null instead of actual null for when you don't have a contentSubArea
key.
6
There's no reason to create a "Dummy Null" to take the place of None. None already serves this purpose. If it weren't acceptable as a dictionary key it would throw an exception because it wasn't hashable.
– g.d.d.c
Aug 11 '11 at 17:15
1
Can you explain a headache that could crop up?
– Ned Batchelder
Aug 11 '11 at 17:15
2
@Ned Batchelder: I think what Mimisbrunnr is referring to is that using None, as opposed to a specific no-valid-key value, is slightly less explicit, which is item 2 in The Zen of Python. Doing it his way may impose some slight performance penalty, but it makes it unambiguous what you are doing. This lack of ambiguity may be a Good Thing® in 6 months when you (or someone else) have to figure out what the code is doing.
– Peter Rowell
Aug 11 '11 at 17:33
1
What Peter Rowell said. Yes None is a full fledged object and can do all those fun object things but it's not clear as to what you mean and want. Additionally if you wind up in a language like C where null is null, this is a habit you do not want to be in.
– zellio
Aug 11 '11 at 17:42
7
"If you change languages <insert any approach here> might not be appropriate". That's kind of a given ... that's why there are different languages with different functionality / approaches. Deciding not to use something in one language because it's unfamiliar or unavailable in another is only limiting your access to the current language's features.
– g.d.d.c
Aug 11 '11 at 17:52
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7030029%2fis-it-reasonable-to-use-none-as-a-dictionary-key-in-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
Any hashable value is a valid Python Dictionary Key. For this reason, None is a perfectly valid candidate. There's no confusion when looking for non-existent keys - the presence of None as a key would not affect the ability to check for whether another key was present. Ex:
>>> d = {1: 'a', 2: 'b', None: 'c'}
>>> 1 in d
True
>>> 5 in d
False
>>> None in d
True
There's no conflict, and you can test for it just like normal. It shouldn't cause you a problem. The standard 1-to-1 Key-Value association still exists, so you can't have multiple things in the None key, but using None as a key shouldn't pose a problem by itself.
add a comment |
Any hashable value is a valid Python Dictionary Key. For this reason, None is a perfectly valid candidate. There's no confusion when looking for non-existent keys - the presence of None as a key would not affect the ability to check for whether another key was present. Ex:
>>> d = {1: 'a', 2: 'b', None: 'c'}
>>> 1 in d
True
>>> 5 in d
False
>>> None in d
True
There's no conflict, and you can test for it just like normal. It shouldn't cause you a problem. The standard 1-to-1 Key-Value association still exists, so you can't have multiple things in the None key, but using None as a key shouldn't pose a problem by itself.
add a comment |
Any hashable value is a valid Python Dictionary Key. For this reason, None is a perfectly valid candidate. There's no confusion when looking for non-existent keys - the presence of None as a key would not affect the ability to check for whether another key was present. Ex:
>>> d = {1: 'a', 2: 'b', None: 'c'}
>>> 1 in d
True
>>> 5 in d
False
>>> None in d
True
There's no conflict, and you can test for it just like normal. It shouldn't cause you a problem. The standard 1-to-1 Key-Value association still exists, so you can't have multiple things in the None key, but using None as a key shouldn't pose a problem by itself.
Any hashable value is a valid Python Dictionary Key. For this reason, None is a perfectly valid candidate. There's no confusion when looking for non-existent keys - the presence of None as a key would not affect the ability to check for whether another key was present. Ex:
>>> d = {1: 'a', 2: 'b', None: 'c'}
>>> 1 in d
True
>>> 5 in d
False
>>> None in d
True
There's no conflict, and you can test for it just like normal. It shouldn't cause you a problem. The standard 1-to-1 Key-Value association still exists, so you can't have multiple things in the None key, but using None as a key shouldn't pose a problem by itself.
answered Aug 11 '11 at 17:12
g.d.d.cg.d.d.c
34.5k77194
34.5k77194
add a comment |
add a comment |
None
is not special in any particular way, it's just another python value. Its only distinction is that it happens to be the return value of a function that doesn't specify any other return value, and it also happens to be a common default value (the default arg of dict.get()
, for instance).
You won't cause any run-time conflicts using such a key, but you should ask yourself if that's really a meaningful value to use for a key. It's often more helpful, from the point of view of reading code and understanding what it does, to use a designated instance for special values. Something like:
NoSubContent = SubContentArea(name=None)
{"contentArea":
{NoSubContent:[standards],
SubContentArea(name="Fruits"): ['apples', 'bananas']}}
1
Doesn't this approach just move the use of None down a level? I was thinking it might be better to only set values that have meanings. Then None represents empty data, and errors indicate problems with data (assuming proper validation and requirements such as allowing null or requiring not null).
– japhyr
Aug 11 '11 at 17:23
1
Like I said, there's nothing really special aboutNone
, and I don't think I'd hesitate to use it as a key in a dict if it were obvious what that must mean for that dict; but if the dict is reasonably heterogeneous, or visible across a large part of the program; adding some meaning to the type of the key could be helpful. It's not so much a question of avoiding theNone
value as picking a unity value with a type that explains itself better thanNone
can.
– SingleNegationElimination
Aug 11 '11 at 17:31
I accepted gddc's answer, but upvoted this answer as well. Using None is working so far, but I can see the advantages to creating a specific key to represent None in a specific context.
– japhyr
Aug 11 '11 at 22:10
I don't think you want to 'use a key to representNone
' that's absurd, just useNone
if you need to representNone
. On the other hand, you might useNone
to represent a degenerate case of your particular application domain, or that could be confusing so you use a designated instance of another class to represent that degenerate case.
– SingleNegationElimination
Aug 12 '11 at 13:03
IsNone
in any possible way similar to 'void' data type present in C/C++.
– darth_coder
May 31 '15 at 6:01
add a comment |
None
is not special in any particular way, it's just another python value. Its only distinction is that it happens to be the return value of a function that doesn't specify any other return value, and it also happens to be a common default value (the default arg of dict.get()
, for instance).
You won't cause any run-time conflicts using such a key, but you should ask yourself if that's really a meaningful value to use for a key. It's often more helpful, from the point of view of reading code and understanding what it does, to use a designated instance for special values. Something like:
NoSubContent = SubContentArea(name=None)
{"contentArea":
{NoSubContent:[standards],
SubContentArea(name="Fruits"): ['apples', 'bananas']}}
1
Doesn't this approach just move the use of None down a level? I was thinking it might be better to only set values that have meanings. Then None represents empty data, and errors indicate problems with data (assuming proper validation and requirements such as allowing null or requiring not null).
– japhyr
Aug 11 '11 at 17:23
1
Like I said, there's nothing really special aboutNone
, and I don't think I'd hesitate to use it as a key in a dict if it were obvious what that must mean for that dict; but if the dict is reasonably heterogeneous, or visible across a large part of the program; adding some meaning to the type of the key could be helpful. It's not so much a question of avoiding theNone
value as picking a unity value with a type that explains itself better thanNone
can.
– SingleNegationElimination
Aug 11 '11 at 17:31
I accepted gddc's answer, but upvoted this answer as well. Using None is working so far, but I can see the advantages to creating a specific key to represent None in a specific context.
– japhyr
Aug 11 '11 at 22:10
I don't think you want to 'use a key to representNone
' that's absurd, just useNone
if you need to representNone
. On the other hand, you might useNone
to represent a degenerate case of your particular application domain, or that could be confusing so you use a designated instance of another class to represent that degenerate case.
– SingleNegationElimination
Aug 12 '11 at 13:03
IsNone
in any possible way similar to 'void' data type present in C/C++.
– darth_coder
May 31 '15 at 6:01
add a comment |
None
is not special in any particular way, it's just another python value. Its only distinction is that it happens to be the return value of a function that doesn't specify any other return value, and it also happens to be a common default value (the default arg of dict.get()
, for instance).
You won't cause any run-time conflicts using such a key, but you should ask yourself if that's really a meaningful value to use for a key. It's often more helpful, from the point of view of reading code and understanding what it does, to use a designated instance for special values. Something like:
NoSubContent = SubContentArea(name=None)
{"contentArea":
{NoSubContent:[standards],
SubContentArea(name="Fruits"): ['apples', 'bananas']}}
None
is not special in any particular way, it's just another python value. Its only distinction is that it happens to be the return value of a function that doesn't specify any other return value, and it also happens to be a common default value (the default arg of dict.get()
, for instance).
You won't cause any run-time conflicts using such a key, but you should ask yourself if that's really a meaningful value to use for a key. It's often more helpful, from the point of view of reading code and understanding what it does, to use a designated instance for special values. Something like:
NoSubContent = SubContentArea(name=None)
{"contentArea":
{NoSubContent:[standards],
SubContentArea(name="Fruits"): ['apples', 'bananas']}}
answered Aug 11 '11 at 17:16
SingleNegationEliminationSingleNegationElimination
112k18213260
112k18213260
1
Doesn't this approach just move the use of None down a level? I was thinking it might be better to only set values that have meanings. Then None represents empty data, and errors indicate problems with data (assuming proper validation and requirements such as allowing null or requiring not null).
– japhyr
Aug 11 '11 at 17:23
1
Like I said, there's nothing really special aboutNone
, and I don't think I'd hesitate to use it as a key in a dict if it were obvious what that must mean for that dict; but if the dict is reasonably heterogeneous, or visible across a large part of the program; adding some meaning to the type of the key could be helpful. It's not so much a question of avoiding theNone
value as picking a unity value with a type that explains itself better thanNone
can.
– SingleNegationElimination
Aug 11 '11 at 17:31
I accepted gddc's answer, but upvoted this answer as well. Using None is working so far, but I can see the advantages to creating a specific key to represent None in a specific context.
– japhyr
Aug 11 '11 at 22:10
I don't think you want to 'use a key to representNone
' that's absurd, just useNone
if you need to representNone
. On the other hand, you might useNone
to represent a degenerate case of your particular application domain, or that could be confusing so you use a designated instance of another class to represent that degenerate case.
– SingleNegationElimination
Aug 12 '11 at 13:03
IsNone
in any possible way similar to 'void' data type present in C/C++.
– darth_coder
May 31 '15 at 6:01
add a comment |
1
Doesn't this approach just move the use of None down a level? I was thinking it might be better to only set values that have meanings. Then None represents empty data, and errors indicate problems with data (assuming proper validation and requirements such as allowing null or requiring not null).
– japhyr
Aug 11 '11 at 17:23
1
Like I said, there's nothing really special aboutNone
, and I don't think I'd hesitate to use it as a key in a dict if it were obvious what that must mean for that dict; but if the dict is reasonably heterogeneous, or visible across a large part of the program; adding some meaning to the type of the key could be helpful. It's not so much a question of avoiding theNone
value as picking a unity value with a type that explains itself better thanNone
can.
– SingleNegationElimination
Aug 11 '11 at 17:31
I accepted gddc's answer, but upvoted this answer as well. Using None is working so far, but I can see the advantages to creating a specific key to represent None in a specific context.
– japhyr
Aug 11 '11 at 22:10
I don't think you want to 'use a key to representNone
' that's absurd, just useNone
if you need to representNone
. On the other hand, you might useNone
to represent a degenerate case of your particular application domain, or that could be confusing so you use a designated instance of another class to represent that degenerate case.
– SingleNegationElimination
Aug 12 '11 at 13:03
IsNone
in any possible way similar to 'void' data type present in C/C++.
– darth_coder
May 31 '15 at 6:01
1
1
Doesn't this approach just move the use of None down a level? I was thinking it might be better to only set values that have meanings. Then None represents empty data, and errors indicate problems with data (assuming proper validation and requirements such as allowing null or requiring not null).
– japhyr
Aug 11 '11 at 17:23
Doesn't this approach just move the use of None down a level? I was thinking it might be better to only set values that have meanings. Then None represents empty data, and errors indicate problems with data (assuming proper validation and requirements such as allowing null or requiring not null).
– japhyr
Aug 11 '11 at 17:23
1
1
Like I said, there's nothing really special about
None
, and I don't think I'd hesitate to use it as a key in a dict if it were obvious what that must mean for that dict; but if the dict is reasonably heterogeneous, or visible across a large part of the program; adding some meaning to the type of the key could be helpful. It's not so much a question of avoiding the None
value as picking a unity value with a type that explains itself better than None
can.– SingleNegationElimination
Aug 11 '11 at 17:31
Like I said, there's nothing really special about
None
, and I don't think I'd hesitate to use it as a key in a dict if it were obvious what that must mean for that dict; but if the dict is reasonably heterogeneous, or visible across a large part of the program; adding some meaning to the type of the key could be helpful. It's not so much a question of avoiding the None
value as picking a unity value with a type that explains itself better than None
can.– SingleNegationElimination
Aug 11 '11 at 17:31
I accepted gddc's answer, but upvoted this answer as well. Using None is working so far, but I can see the advantages to creating a specific key to represent None in a specific context.
– japhyr
Aug 11 '11 at 22:10
I accepted gddc's answer, but upvoted this answer as well. Using None is working so far, but I can see the advantages to creating a specific key to represent None in a specific context.
– japhyr
Aug 11 '11 at 22:10
I don't think you want to 'use a key to represent
None
' that's absurd, just use None
if you need to represent None
. On the other hand, you might use None
to represent a degenerate case of your particular application domain, or that could be confusing so you use a designated instance of another class to represent that degenerate case.– SingleNegationElimination
Aug 12 '11 at 13:03
I don't think you want to 'use a key to represent
None
' that's absurd, just use None
if you need to represent None
. On the other hand, you might use None
to represent a degenerate case of your particular application domain, or that could be confusing so you use a designated instance of another class to represent that degenerate case.– SingleNegationElimination
Aug 12 '11 at 13:03
Is
None
in any possible way similar to 'void' data type present in C/C++.– darth_coder
May 31 '15 at 6:01
Is
None
in any possible way similar to 'void' data type present in C/C++.– darth_coder
May 31 '15 at 6:01
add a comment |
You want trouble? here we go:
>>> json.loads(json.dumps({None:None}))
{u'null': None}
So yea, better stay away from json if you do use None
as a key. You can patch this by custom (de/)serializer, but I would advise against use of None
as a key in the first place.
add a comment |
You want trouble? here we go:
>>> json.loads(json.dumps({None:None}))
{u'null': None}
So yea, better stay away from json if you do use None
as a key. You can patch this by custom (de/)serializer, but I would advise against use of None
as a key in the first place.
add a comment |
You want trouble? here we go:
>>> json.loads(json.dumps({None:None}))
{u'null': None}
So yea, better stay away from json if you do use None
as a key. You can patch this by custom (de/)serializer, but I would advise against use of None
as a key in the first place.
You want trouble? here we go:
>>> json.loads(json.dumps({None:None}))
{u'null': None}
So yea, better stay away from json if you do use None
as a key. You can patch this by custom (de/)serializer, but I would advise against use of None
as a key in the first place.
answered Jan 13 '16 at 16:46
Maciej UrbańskiMaciej Urbański
29129
29129
add a comment |
add a comment |
It seems to me, the larger, later problem is this. If your process is creating pairs and some pairs have a "None" key, then it will overwrite all the previous None pairs. Your dictionary will silently throw out values because you had duplicate None keys. No?
I was going to use None as a key, thought "I'll just see what stackoverflow has to say about it" This persuaded me not to
– Dan
Mar 22 '15 at 11:27
1
What if you had a "5" key. Wouldn't that get silently overwritten too? Why is the None object special in that way?
– Mad Physicist
Dec 31 '15 at 13:24
@MadPhysicist - It's not. Dictionaries are always 1-to-1 key-to-value containers. Reassigning any key will replace whatever was in the key previously.
– g.d.d.c
Feb 26 '16 at 15:33
1
@g.d.d.c. I agree. My point is then thatNone
is just as valid a key as5
. There's no good reason not to use it if it is convenient to do so.
– Mad Physicist
Feb 26 '16 at 16:01
add a comment |
It seems to me, the larger, later problem is this. If your process is creating pairs and some pairs have a "None" key, then it will overwrite all the previous None pairs. Your dictionary will silently throw out values because you had duplicate None keys. No?
I was going to use None as a key, thought "I'll just see what stackoverflow has to say about it" This persuaded me not to
– Dan
Mar 22 '15 at 11:27
1
What if you had a "5" key. Wouldn't that get silently overwritten too? Why is the None object special in that way?
– Mad Physicist
Dec 31 '15 at 13:24
@MadPhysicist - It's not. Dictionaries are always 1-to-1 key-to-value containers. Reassigning any key will replace whatever was in the key previously.
– g.d.d.c
Feb 26 '16 at 15:33
1
@g.d.d.c. I agree. My point is then thatNone
is just as valid a key as5
. There's no good reason not to use it if it is convenient to do so.
– Mad Physicist
Feb 26 '16 at 16:01
add a comment |
It seems to me, the larger, later problem is this. If your process is creating pairs and some pairs have a "None" key, then it will overwrite all the previous None pairs. Your dictionary will silently throw out values because you had duplicate None keys. No?
It seems to me, the larger, later problem is this. If your process is creating pairs and some pairs have a "None" key, then it will overwrite all the previous None pairs. Your dictionary will silently throw out values because you had duplicate None keys. No?
answered Apr 24 '14 at 15:28
user3023464user3023464
212
212
I was going to use None as a key, thought "I'll just see what stackoverflow has to say about it" This persuaded me not to
– Dan
Mar 22 '15 at 11:27
1
What if you had a "5" key. Wouldn't that get silently overwritten too? Why is the None object special in that way?
– Mad Physicist
Dec 31 '15 at 13:24
@MadPhysicist - It's not. Dictionaries are always 1-to-1 key-to-value containers. Reassigning any key will replace whatever was in the key previously.
– g.d.d.c
Feb 26 '16 at 15:33
1
@g.d.d.c. I agree. My point is then thatNone
is just as valid a key as5
. There's no good reason not to use it if it is convenient to do so.
– Mad Physicist
Feb 26 '16 at 16:01
add a comment |
I was going to use None as a key, thought "I'll just see what stackoverflow has to say about it" This persuaded me not to
– Dan
Mar 22 '15 at 11:27
1
What if you had a "5" key. Wouldn't that get silently overwritten too? Why is the None object special in that way?
– Mad Physicist
Dec 31 '15 at 13:24
@MadPhysicist - It's not. Dictionaries are always 1-to-1 key-to-value containers. Reassigning any key will replace whatever was in the key previously.
– g.d.d.c
Feb 26 '16 at 15:33
1
@g.d.d.c. I agree. My point is then thatNone
is just as valid a key as5
. There's no good reason not to use it if it is convenient to do so.
– Mad Physicist
Feb 26 '16 at 16:01
I was going to use None as a key, thought "I'll just see what stackoverflow has to say about it" This persuaded me not to
– Dan
Mar 22 '15 at 11:27
I was going to use None as a key, thought "I'll just see what stackoverflow has to say about it" This persuaded me not to
– Dan
Mar 22 '15 at 11:27
1
1
What if you had a "5" key. Wouldn't that get silently overwritten too? Why is the None object special in that way?
– Mad Physicist
Dec 31 '15 at 13:24
What if you had a "5" key. Wouldn't that get silently overwritten too? Why is the None object special in that way?
– Mad Physicist
Dec 31 '15 at 13:24
@MadPhysicist - It's not. Dictionaries are always 1-to-1 key-to-value containers. Reassigning any key will replace whatever was in the key previously.
– g.d.d.c
Feb 26 '16 at 15:33
@MadPhysicist - It's not. Dictionaries are always 1-to-1 key-to-value containers. Reassigning any key will replace whatever was in the key previously.
– g.d.d.c
Feb 26 '16 at 15:33
1
1
@g.d.d.c. I agree. My point is then that
None
is just as valid a key as 5
. There's no good reason not to use it if it is convenient to do so.– Mad Physicist
Feb 26 '16 at 16:01
@g.d.d.c. I agree. My point is then that
None
is just as valid a key as 5
. There's no good reason not to use it if it is convenient to do so.– Mad Physicist
Feb 26 '16 at 16:01
add a comment |
Funny though, even this works :
d = {None: 'None'}
In [10]: None in d
Out[10]: True
add a comment |
Funny though, even this works :
d = {None: 'None'}
In [10]: None in d
Out[10]: True
add a comment |
Funny though, even this works :
d = {None: 'None'}
In [10]: None in d
Out[10]: True
Funny though, even this works :
d = {None: 'None'}
In [10]: None in d
Out[10]: True
answered Jul 7 '14 at 12:29
sb32134sb32134
153214
153214
add a comment |
add a comment |
No. It will only cause headaches in the future. Use a dummy null instead of actual null for when you don't have a contentSubArea
key.
6
There's no reason to create a "Dummy Null" to take the place of None. None already serves this purpose. If it weren't acceptable as a dictionary key it would throw an exception because it wasn't hashable.
– g.d.d.c
Aug 11 '11 at 17:15
1
Can you explain a headache that could crop up?
– Ned Batchelder
Aug 11 '11 at 17:15
2
@Ned Batchelder: I think what Mimisbrunnr is referring to is that using None, as opposed to a specific no-valid-key value, is slightly less explicit, which is item 2 in The Zen of Python. Doing it his way may impose some slight performance penalty, but it makes it unambiguous what you are doing. This lack of ambiguity may be a Good Thing® in 6 months when you (or someone else) have to figure out what the code is doing.
– Peter Rowell
Aug 11 '11 at 17:33
1
What Peter Rowell said. Yes None is a full fledged object and can do all those fun object things but it's not clear as to what you mean and want. Additionally if you wind up in a language like C where null is null, this is a habit you do not want to be in.
– zellio
Aug 11 '11 at 17:42
7
"If you change languages <insert any approach here> might not be appropriate". That's kind of a given ... that's why there are different languages with different functionality / approaches. Deciding not to use something in one language because it's unfamiliar or unavailable in another is only limiting your access to the current language's features.
– g.d.d.c
Aug 11 '11 at 17:52
add a comment |
No. It will only cause headaches in the future. Use a dummy null instead of actual null for when you don't have a contentSubArea
key.
6
There's no reason to create a "Dummy Null" to take the place of None. None already serves this purpose. If it weren't acceptable as a dictionary key it would throw an exception because it wasn't hashable.
– g.d.d.c
Aug 11 '11 at 17:15
1
Can you explain a headache that could crop up?
– Ned Batchelder
Aug 11 '11 at 17:15
2
@Ned Batchelder: I think what Mimisbrunnr is referring to is that using None, as opposed to a specific no-valid-key value, is slightly less explicit, which is item 2 in The Zen of Python. Doing it his way may impose some slight performance penalty, but it makes it unambiguous what you are doing. This lack of ambiguity may be a Good Thing® in 6 months when you (or someone else) have to figure out what the code is doing.
– Peter Rowell
Aug 11 '11 at 17:33
1
What Peter Rowell said. Yes None is a full fledged object and can do all those fun object things but it's not clear as to what you mean and want. Additionally if you wind up in a language like C where null is null, this is a habit you do not want to be in.
– zellio
Aug 11 '11 at 17:42
7
"If you change languages <insert any approach here> might not be appropriate". That's kind of a given ... that's why there are different languages with different functionality / approaches. Deciding not to use something in one language because it's unfamiliar or unavailable in another is only limiting your access to the current language's features.
– g.d.d.c
Aug 11 '11 at 17:52
add a comment |
No. It will only cause headaches in the future. Use a dummy null instead of actual null for when you don't have a contentSubArea
key.
No. It will only cause headaches in the future. Use a dummy null instead of actual null for when you don't have a contentSubArea
key.
answered Aug 11 '11 at 17:12
zelliozellio
17.5k13153
17.5k13153
6
There's no reason to create a "Dummy Null" to take the place of None. None already serves this purpose. If it weren't acceptable as a dictionary key it would throw an exception because it wasn't hashable.
– g.d.d.c
Aug 11 '11 at 17:15
1
Can you explain a headache that could crop up?
– Ned Batchelder
Aug 11 '11 at 17:15
2
@Ned Batchelder: I think what Mimisbrunnr is referring to is that using None, as opposed to a specific no-valid-key value, is slightly less explicit, which is item 2 in The Zen of Python. Doing it his way may impose some slight performance penalty, but it makes it unambiguous what you are doing. This lack of ambiguity may be a Good Thing® in 6 months when you (or someone else) have to figure out what the code is doing.
– Peter Rowell
Aug 11 '11 at 17:33
1
What Peter Rowell said. Yes None is a full fledged object and can do all those fun object things but it's not clear as to what you mean and want. Additionally if you wind up in a language like C where null is null, this is a habit you do not want to be in.
– zellio
Aug 11 '11 at 17:42
7
"If you change languages <insert any approach here> might not be appropriate". That's kind of a given ... that's why there are different languages with different functionality / approaches. Deciding not to use something in one language because it's unfamiliar or unavailable in another is only limiting your access to the current language's features.
– g.d.d.c
Aug 11 '11 at 17:52
add a comment |
6
There's no reason to create a "Dummy Null" to take the place of None. None already serves this purpose. If it weren't acceptable as a dictionary key it would throw an exception because it wasn't hashable.
– g.d.d.c
Aug 11 '11 at 17:15
1
Can you explain a headache that could crop up?
– Ned Batchelder
Aug 11 '11 at 17:15
2
@Ned Batchelder: I think what Mimisbrunnr is referring to is that using None, as opposed to a specific no-valid-key value, is slightly less explicit, which is item 2 in The Zen of Python. Doing it his way may impose some slight performance penalty, but it makes it unambiguous what you are doing. This lack of ambiguity may be a Good Thing® in 6 months when you (or someone else) have to figure out what the code is doing.
– Peter Rowell
Aug 11 '11 at 17:33
1
What Peter Rowell said. Yes None is a full fledged object and can do all those fun object things but it's not clear as to what you mean and want. Additionally if you wind up in a language like C where null is null, this is a habit you do not want to be in.
– zellio
Aug 11 '11 at 17:42
7
"If you change languages <insert any approach here> might not be appropriate". That's kind of a given ... that's why there are different languages with different functionality / approaches. Deciding not to use something in one language because it's unfamiliar or unavailable in another is only limiting your access to the current language's features.
– g.d.d.c
Aug 11 '11 at 17:52
6
6
There's no reason to create a "Dummy Null" to take the place of None. None already serves this purpose. If it weren't acceptable as a dictionary key it would throw an exception because it wasn't hashable.
– g.d.d.c
Aug 11 '11 at 17:15
There's no reason to create a "Dummy Null" to take the place of None. None already serves this purpose. If it weren't acceptable as a dictionary key it would throw an exception because it wasn't hashable.
– g.d.d.c
Aug 11 '11 at 17:15
1
1
Can you explain a headache that could crop up?
– Ned Batchelder
Aug 11 '11 at 17:15
Can you explain a headache that could crop up?
– Ned Batchelder
Aug 11 '11 at 17:15
2
2
@Ned Batchelder: I think what Mimisbrunnr is referring to is that using None, as opposed to a specific no-valid-key value, is slightly less explicit, which is item 2 in The Zen of Python. Doing it his way may impose some slight performance penalty, but it makes it unambiguous what you are doing. This lack of ambiguity may be a Good Thing® in 6 months when you (or someone else) have to figure out what the code is doing.
– Peter Rowell
Aug 11 '11 at 17:33
@Ned Batchelder: I think what Mimisbrunnr is referring to is that using None, as opposed to a specific no-valid-key value, is slightly less explicit, which is item 2 in The Zen of Python. Doing it his way may impose some slight performance penalty, but it makes it unambiguous what you are doing. This lack of ambiguity may be a Good Thing® in 6 months when you (or someone else) have to figure out what the code is doing.
– Peter Rowell
Aug 11 '11 at 17:33
1
1
What Peter Rowell said. Yes None is a full fledged object and can do all those fun object things but it's not clear as to what you mean and want. Additionally if you wind up in a language like C where null is null, this is a habit you do not want to be in.
– zellio
Aug 11 '11 at 17:42
What Peter Rowell said. Yes None is a full fledged object and can do all those fun object things but it's not clear as to what you mean and want. Additionally if you wind up in a language like C where null is null, this is a habit you do not want to be in.
– zellio
Aug 11 '11 at 17:42
7
7
"If you change languages <insert any approach here> might not be appropriate". That's kind of a given ... that's why there are different languages with different functionality / approaches. Deciding not to use something in one language because it's unfamiliar or unavailable in another is only limiting your access to the current language's features.
– g.d.d.c
Aug 11 '11 at 17:52
"If you change languages <insert any approach here> might not be appropriate". That's kind of a given ... that's why there are different languages with different functionality / approaches. Deciding not to use something in one language because it's unfamiliar or unavailable in another is only limiting your access to the current language's features.
– g.d.d.c
Aug 11 '11 at 17:52
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7030029%2fis-it-reasonable-to-use-none-as-a-dictionary-key-in-python%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
What does cause trouble is using
NaN
as a key. It's deceptive, because it's hashable, but doesn't compare equal to itself. That is:float('nan') == float('nan')
returnsFalse
, as it should, on two Python implementations I've tried. If you use it as a key in a dictionary, it won't raise an exception, and using it as an index will work if and only if it is the sameNaN
object (has the sameid(..)
) — though this might be implementation-dependent. So it might work as expected for a while, and then fail. None of these troubles affectNone
, even just because there is only oneNone
.– Evgeni Sergeev
May 24 '16 at 4:43