Pythonic way of checking for dict keys
up vote
1
down vote
favorite
When checking a python dict for a key, which is the better way here:
(I can't figure how to use dict.get()
to make this cleaner)
if 'y' in self.axes:
ax = self.axes['y'].ax
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
or:
try:
ax = self.axes['y'].ax
except KeyError:
pass
else:
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
The latter way is closer to EAFP but former seems clearer, especially for new code contributors who are scientists first & coders second.
python dictionary
add a comment |
up vote
1
down vote
favorite
When checking a python dict for a key, which is the better way here:
(I can't figure how to use dict.get()
to make this cleaner)
if 'y' in self.axes:
ax = self.axes['y'].ax
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
or:
try:
ax = self.axes['y'].ax
except KeyError:
pass
else:
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
The latter way is closer to EAFP but former seems clearer, especially for new code contributors who are scientists first & coders second.
python dictionary
add a comment |
up vote
1
down vote
favorite
up vote
1
down vote
favorite
When checking a python dict for a key, which is the better way here:
(I can't figure how to use dict.get()
to make this cleaner)
if 'y' in self.axes:
ax = self.axes['y'].ax
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
or:
try:
ax = self.axes['y'].ax
except KeyError:
pass
else:
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
The latter way is closer to EAFP but former seems clearer, especially for new code contributors who are scientists first & coders second.
python dictionary
When checking a python dict for a key, which is the better way here:
(I can't figure how to use dict.get()
to make this cleaner)
if 'y' in self.axes:
ax = self.axes['y'].ax
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
or:
try:
ax = self.axes['y'].ax
except KeyError:
pass
else:
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
The latter way is closer to EAFP but former seems clearer, especially for new code contributors who are scientists first & coders second.
python dictionary
python dictionary
asked Dec 11 at 19:48
kchawla-pi
1111
1111
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
up vote
3
down vote
Both ways are valid and have their own advantages. Checking upfront using an if
statement involve a bit of overheard for each usage, using EAFP involve greater overheads but only for the "wrong" case.
So if you mostly have cases where 'y'
is in self.axes
then EAFP is better, otherwise LBYL is fine.
But if you only are calling this pattern a handful of times, then either will do; or no, use the third approach contextlib.suppress
because this except: pass
is ugly:
from contextlib import suppress
with suppress(KeyError):
ax = self.axes['y'].ax
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
I know that it's considered Pythonic to do "logic by exception", but in every other language it's discouraged, and it creeps me out.
– Reinderien
Dec 12 at 16:28
add a comment |
up vote
3
down vote
Sort of neither, but closer to the first.
y = self.axes.get('y')
if y is not None:
ax = y.ax
coord1[ax] = x0
coord2[ax] = y1 - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
get
is a best-effort function that will (by default) return None
if the key doesn't exist. This approach means you only ever need to do one key lookup.
One of the reasons to prefer this method is that it can be faster than exceptions, depending on your data. To demonstrate,
#!/usr/bin/env python3
from contextlib import suppress
from sys import version
from timeit import timeit
def exception_method(axes, coord):
try:
ax = axes['y']
except KeyError:
pass
else:
coord[ax] = 0
def suppress_method(axes, coord):
with suppress(KeyError):
ax = axes['y']
coord[ax] = 0
def get_method(axes, coord):
ax = axes.get('y')
if ax is not None:
coord[ax] = 0
methods = ((suppress_method, 'contextlib.suppress'),
(exception_method, 'exception swallowing'),
(get_method, 'dict.get'))
def trial(method_index, is_present):
coord = {}
axes = {'y': 0} if is_present else {}
method, desc = methods[method_index]
def run():
method(axes, coord)
REPS = 200000
t = timeit(run, number=REPS)/REPS * 1e6
print(f'Method: {desc:20}, '
f'Key pre-exists: {str(is_present):5}, '
f'Avg time (us): {t:.2f}')
def main():
print(version)
for method in range(3):
for present in (False, True):
trial(method, present)
if __name__ == '__main__':
main()
The output is:
3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
Method: contextlib.suppress , Key pre-exists: False, Avg time (us): 8.86
Method: contextlib.suppress , Key pre-exists: True , Avg time (us): 7.71
Method: exception swallowing, Key pre-exists: False, Avg time (us): 3.70
Method: exception swallowing, Key pre-exists: True , Avg time (us): 2.93
Method: dict.get , Key pre-exists: False, Avg time (us): 2.90
Method: dict.get , Key pre-exists: True , Avg time (us): 3.00
If you can guarantee that in most cases the key will pre-exist, then the exception-swallowing method is marginally fastest. Otherwise, get
is fastest.
2
I wonder if the upcoming syntaxif ax := axis.get('y') is not None: coord[ax] = 0
will bring improvements.
– Mathias Ettinger
Dec 12 at 17:36
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
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: "196"
};
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: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
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%2fcodereview.stackexchange.com%2fquestions%2f209468%2fpythonic-way-of-checking-for-dict-keys%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
3
down vote
Both ways are valid and have their own advantages. Checking upfront using an if
statement involve a bit of overheard for each usage, using EAFP involve greater overheads but only for the "wrong" case.
So if you mostly have cases where 'y'
is in self.axes
then EAFP is better, otherwise LBYL is fine.
But if you only are calling this pattern a handful of times, then either will do; or no, use the third approach contextlib.suppress
because this except: pass
is ugly:
from contextlib import suppress
with suppress(KeyError):
ax = self.axes['y'].ax
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
I know that it's considered Pythonic to do "logic by exception", but in every other language it's discouraged, and it creeps me out.
– Reinderien
Dec 12 at 16:28
add a comment |
up vote
3
down vote
Both ways are valid and have their own advantages. Checking upfront using an if
statement involve a bit of overheard for each usage, using EAFP involve greater overheads but only for the "wrong" case.
So if you mostly have cases where 'y'
is in self.axes
then EAFP is better, otherwise LBYL is fine.
But if you only are calling this pattern a handful of times, then either will do; or no, use the third approach contextlib.suppress
because this except: pass
is ugly:
from contextlib import suppress
with suppress(KeyError):
ax = self.axes['y'].ax
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
I know that it's considered Pythonic to do "logic by exception", but in every other language it's discouraged, and it creeps me out.
– Reinderien
Dec 12 at 16:28
add a comment |
up vote
3
down vote
up vote
3
down vote
Both ways are valid and have their own advantages. Checking upfront using an if
statement involve a bit of overheard for each usage, using EAFP involve greater overheads but only for the "wrong" case.
So if you mostly have cases where 'y'
is in self.axes
then EAFP is better, otherwise LBYL is fine.
But if you only are calling this pattern a handful of times, then either will do; or no, use the third approach contextlib.suppress
because this except: pass
is ugly:
from contextlib import suppress
with suppress(KeyError):
ax = self.axes['y'].ax
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
Both ways are valid and have their own advantages. Checking upfront using an if
statement involve a bit of overheard for each usage, using EAFP involve greater overheads but only for the "wrong" case.
So if you mostly have cases where 'y'
is in self.axes
then EAFP is better, otherwise LBYL is fine.
But if you only are calling this pattern a handful of times, then either will do; or no, use the third approach contextlib.suppress
because this except: pass
is ugly:
from contextlib import suppress
with suppress(KeyError):
ax = self.axes['y'].ax
coord1[ax] = x0
coord2[ax] = (y1) - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
edited Dec 11 at 23:01
IEatBagels
8,85323178
8,85323178
answered Dec 11 at 22:33
Mathias Ettinger
23.3k33181
23.3k33181
I know that it's considered Pythonic to do "logic by exception", but in every other language it's discouraged, and it creeps me out.
– Reinderien
Dec 12 at 16:28
add a comment |
I know that it's considered Pythonic to do "logic by exception", but in every other language it's discouraged, and it creeps me out.
– Reinderien
Dec 12 at 16:28
I know that it's considered Pythonic to do "logic by exception", but in every other language it's discouraged, and it creeps me out.
– Reinderien
Dec 12 at 16:28
I know that it's considered Pythonic to do "logic by exception", but in every other language it's discouraged, and it creeps me out.
– Reinderien
Dec 12 at 16:28
add a comment |
up vote
3
down vote
Sort of neither, but closer to the first.
y = self.axes.get('y')
if y is not None:
ax = y.ax
coord1[ax] = x0
coord2[ax] = y1 - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
get
is a best-effort function that will (by default) return None
if the key doesn't exist. This approach means you only ever need to do one key lookup.
One of the reasons to prefer this method is that it can be faster than exceptions, depending on your data. To demonstrate,
#!/usr/bin/env python3
from contextlib import suppress
from sys import version
from timeit import timeit
def exception_method(axes, coord):
try:
ax = axes['y']
except KeyError:
pass
else:
coord[ax] = 0
def suppress_method(axes, coord):
with suppress(KeyError):
ax = axes['y']
coord[ax] = 0
def get_method(axes, coord):
ax = axes.get('y')
if ax is not None:
coord[ax] = 0
methods = ((suppress_method, 'contextlib.suppress'),
(exception_method, 'exception swallowing'),
(get_method, 'dict.get'))
def trial(method_index, is_present):
coord = {}
axes = {'y': 0} if is_present else {}
method, desc = methods[method_index]
def run():
method(axes, coord)
REPS = 200000
t = timeit(run, number=REPS)/REPS * 1e6
print(f'Method: {desc:20}, '
f'Key pre-exists: {str(is_present):5}, '
f'Avg time (us): {t:.2f}')
def main():
print(version)
for method in range(3):
for present in (False, True):
trial(method, present)
if __name__ == '__main__':
main()
The output is:
3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
Method: contextlib.suppress , Key pre-exists: False, Avg time (us): 8.86
Method: contextlib.suppress , Key pre-exists: True , Avg time (us): 7.71
Method: exception swallowing, Key pre-exists: False, Avg time (us): 3.70
Method: exception swallowing, Key pre-exists: True , Avg time (us): 2.93
Method: dict.get , Key pre-exists: False, Avg time (us): 2.90
Method: dict.get , Key pre-exists: True , Avg time (us): 3.00
If you can guarantee that in most cases the key will pre-exist, then the exception-swallowing method is marginally fastest. Otherwise, get
is fastest.
2
I wonder if the upcoming syntaxif ax := axis.get('y') is not None: coord[ax] = 0
will bring improvements.
– Mathias Ettinger
Dec 12 at 17:36
add a comment |
up vote
3
down vote
Sort of neither, but closer to the first.
y = self.axes.get('y')
if y is not None:
ax = y.ax
coord1[ax] = x0
coord2[ax] = y1 - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
get
is a best-effort function that will (by default) return None
if the key doesn't exist. This approach means you only ever need to do one key lookup.
One of the reasons to prefer this method is that it can be faster than exceptions, depending on your data. To demonstrate,
#!/usr/bin/env python3
from contextlib import suppress
from sys import version
from timeit import timeit
def exception_method(axes, coord):
try:
ax = axes['y']
except KeyError:
pass
else:
coord[ax] = 0
def suppress_method(axes, coord):
with suppress(KeyError):
ax = axes['y']
coord[ax] = 0
def get_method(axes, coord):
ax = axes.get('y')
if ax is not None:
coord[ax] = 0
methods = ((suppress_method, 'contextlib.suppress'),
(exception_method, 'exception swallowing'),
(get_method, 'dict.get'))
def trial(method_index, is_present):
coord = {}
axes = {'y': 0} if is_present else {}
method, desc = methods[method_index]
def run():
method(axes, coord)
REPS = 200000
t = timeit(run, number=REPS)/REPS * 1e6
print(f'Method: {desc:20}, '
f'Key pre-exists: {str(is_present):5}, '
f'Avg time (us): {t:.2f}')
def main():
print(version)
for method in range(3):
for present in (False, True):
trial(method, present)
if __name__ == '__main__':
main()
The output is:
3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
Method: contextlib.suppress , Key pre-exists: False, Avg time (us): 8.86
Method: contextlib.suppress , Key pre-exists: True , Avg time (us): 7.71
Method: exception swallowing, Key pre-exists: False, Avg time (us): 3.70
Method: exception swallowing, Key pre-exists: True , Avg time (us): 2.93
Method: dict.get , Key pre-exists: False, Avg time (us): 2.90
Method: dict.get , Key pre-exists: True , Avg time (us): 3.00
If you can guarantee that in most cases the key will pre-exist, then the exception-swallowing method is marginally fastest. Otherwise, get
is fastest.
2
I wonder if the upcoming syntaxif ax := axis.get('y') is not None: coord[ax] = 0
will bring improvements.
– Mathias Ettinger
Dec 12 at 17:36
add a comment |
up vote
3
down vote
up vote
3
down vote
Sort of neither, but closer to the first.
y = self.axes.get('y')
if y is not None:
ax = y.ax
coord1[ax] = x0
coord2[ax] = y1 - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
get
is a best-effort function that will (by default) return None
if the key doesn't exist. This approach means you only ever need to do one key lookup.
One of the reasons to prefer this method is that it can be faster than exceptions, depending on your data. To demonstrate,
#!/usr/bin/env python3
from contextlib import suppress
from sys import version
from timeit import timeit
def exception_method(axes, coord):
try:
ax = axes['y']
except KeyError:
pass
else:
coord[ax] = 0
def suppress_method(axes, coord):
with suppress(KeyError):
ax = axes['y']
coord[ax] = 0
def get_method(axes, coord):
ax = axes.get('y')
if ax is not None:
coord[ax] = 0
methods = ((suppress_method, 'contextlib.suppress'),
(exception_method, 'exception swallowing'),
(get_method, 'dict.get'))
def trial(method_index, is_present):
coord = {}
axes = {'y': 0} if is_present else {}
method, desc = methods[method_index]
def run():
method(axes, coord)
REPS = 200000
t = timeit(run, number=REPS)/REPS * 1e6
print(f'Method: {desc:20}, '
f'Key pre-exists: {str(is_present):5}, '
f'Avg time (us): {t:.2f}')
def main():
print(version)
for method in range(3):
for present in (False, True):
trial(method, present)
if __name__ == '__main__':
main()
The output is:
3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
Method: contextlib.suppress , Key pre-exists: False, Avg time (us): 8.86
Method: contextlib.suppress , Key pre-exists: True , Avg time (us): 7.71
Method: exception swallowing, Key pre-exists: False, Avg time (us): 3.70
Method: exception swallowing, Key pre-exists: True , Avg time (us): 2.93
Method: dict.get , Key pre-exists: False, Avg time (us): 2.90
Method: dict.get , Key pre-exists: True , Avg time (us): 3.00
If you can guarantee that in most cases the key will pre-exist, then the exception-swallowing method is marginally fastest. Otherwise, get
is fastest.
Sort of neither, but closer to the first.
y = self.axes.get('y')
if y is not None:
ax = y.ax
coord1[ax] = x0
coord2[ax] = y1 - height[ax]
coord3[ax] = x0 + width[ax]
coord4[ax] = y1
get
is a best-effort function that will (by default) return None
if the key doesn't exist. This approach means you only ever need to do one key lookup.
One of the reasons to prefer this method is that it can be faster than exceptions, depending on your data. To demonstrate,
#!/usr/bin/env python3
from contextlib import suppress
from sys import version
from timeit import timeit
def exception_method(axes, coord):
try:
ax = axes['y']
except KeyError:
pass
else:
coord[ax] = 0
def suppress_method(axes, coord):
with suppress(KeyError):
ax = axes['y']
coord[ax] = 0
def get_method(axes, coord):
ax = axes.get('y')
if ax is not None:
coord[ax] = 0
methods = ((suppress_method, 'contextlib.suppress'),
(exception_method, 'exception swallowing'),
(get_method, 'dict.get'))
def trial(method_index, is_present):
coord = {}
axes = {'y': 0} if is_present else {}
method, desc = methods[method_index]
def run():
method(axes, coord)
REPS = 200000
t = timeit(run, number=REPS)/REPS * 1e6
print(f'Method: {desc:20}, '
f'Key pre-exists: {str(is_present):5}, '
f'Avg time (us): {t:.2f}')
def main():
print(version)
for method in range(3):
for present in (False, True):
trial(method, present)
if __name__ == '__main__':
main()
The output is:
3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
Method: contextlib.suppress , Key pre-exists: False, Avg time (us): 8.86
Method: contextlib.suppress , Key pre-exists: True , Avg time (us): 7.71
Method: exception swallowing, Key pre-exists: False, Avg time (us): 3.70
Method: exception swallowing, Key pre-exists: True , Avg time (us): 2.93
Method: dict.get , Key pre-exists: False, Avg time (us): 2.90
Method: dict.get , Key pre-exists: True , Avg time (us): 3.00
If you can guarantee that in most cases the key will pre-exist, then the exception-swallowing method is marginally fastest. Otherwise, get
is fastest.
edited Dec 12 at 17:12
answered Dec 11 at 20:55
Reinderien
2,047616
2,047616
2
I wonder if the upcoming syntaxif ax := axis.get('y') is not None: coord[ax] = 0
will bring improvements.
– Mathias Ettinger
Dec 12 at 17:36
add a comment |
2
I wonder if the upcoming syntaxif ax := axis.get('y') is not None: coord[ax] = 0
will bring improvements.
– Mathias Ettinger
Dec 12 at 17:36
2
2
I wonder if the upcoming syntax
if ax := axis.get('y') is not None: coord[ax] = 0
will bring improvements.– Mathias Ettinger
Dec 12 at 17:36
I wonder if the upcoming syntax
if ax := axis.get('y') is not None: coord[ax] = 0
will bring improvements.– Mathias Ettinger
Dec 12 at 17:36
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- 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.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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%2fcodereview.stackexchange.com%2fquestions%2f209468%2fpythonic-way-of-checking-for-dict-keys%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