0

I am beginner in python and I'm wondering which approach is better assuming I have the following code and which one should be used in production.

d = {}
d['a'] = set([0,1,2,0])
d['b'] = set([1,2,1,2])

Approach 1:

try:
    print(d['c'])
except:
    print(set())

Approach 2:

try:
   ans = d['c']
except:
    ans = set()
print(ans)

Approach 3:

if 'c' in d.keys():
    print(d['c'])
else:
    print(set())

Approach 4:

if 'a' in d.keys():
    ans = d['c']
else:
    ans = set()
print(ans)
Zoli
  • 831
  • 1
  • 11
  • 27
  • 2
    For this kind of thing there's `dict.get` (or `defaultdict` if you have lots of these). – georg Jan 17 '15 at 14:09
  • 2
    [Don't use bare `except` clauses.](https://docs.python.org/2/howto/doanddont.html#except) – Ashwini Chaudhary Jan 17 '15 at 14:10
  • 2
    Note that is more of a [codereview](http://codereview.stackexchange.com) question; there's no problem to be solved here. – DSM Jan 17 '15 at 14:11
  • 2
    don't use `if 'c' in d.keys():` either, `if 'c' in d:` does the same thing. What do you want to do with ans? – Padraic Cunningham Jan 17 '15 at 14:12
  • Programmers post on the subject: [Python - 'if foo in dict' vs 'try: dict\[foo\]']([Python - 'if foo in dict' vs 'try: dict\[foo\]']([Python - 'if foo in dict' vs 'try: dict\[foo\]'](http://programmers.stackexchange.com/q/225238))). Then there is [Python: is "Except keyerror" faster than "if key in dict"?](http://stackoverflow.com/q/20308567) here on SO. In fact, your question is a dupe of the latter. – Martijn Pieters Jan 17 '15 at 14:14

1 Answers1

0

A try and except clause works like this. The code under the try statement is executed. As soon as an exception happens in the try clause it jumps to the except statement. If the error that occurs corresponds to the defined exception that except clause is executed.

This is what you would want to do:

d = {}
d['a'] = set([0,1,2,0])
d['b'] = set([1,2,1,2])

try:
    print(d['c'])     #if this doesn't exist a KeyError is raised
                     #thus it immediately jumps to the except clause
except KeyError:
    print("No such key in the dictionary")

But if you print(d['a']) no exception occurs thus the except clause is skipped.

Loupi
  • 550
  • 6
  • 14