0

The problem

I have the following list in Python 3.6

Piko = {}
Piko['Name']='Luke'

I am trying to write a function that give the value of the element if it exist and is set and give None otherwise. For example:

  • INPUT: isset(Piko['Name']) OUTPUT: Luke
  • INPUT: isset(Piko['Surname']) OUTPUT: None

What I have tried

1st try; based on my know how:

def isset1(x):
    try:
        x
    except KeyError:
        print(None)
    else:
        print(x)

2nd try; based on this answer:

def isset2(x):
    try:
        t=x
    except IndexError:
        print(None)

3rd try; based on this answer:

def isset3(x):
    try:
        x
    except Exception:
        print(None)
    else:
        print(x)

Any one of the previous gives me KeyError: 'Surname' error and does not output None as I wanted. Can anybody help me explaining how could I manage correctly the KeyError?

martineau
  • 119,623
  • 25
  • 170
  • 301
Nicolaesse
  • 2,554
  • 12
  • 46
  • 71

2 Answers2

4
Piko.get('Surname')

Piko.get('Surname', None)

are identical and return None since "Surname" is not in your dictionary.

For future reference you can quickly discover this from the Python shell (eg ipython) by typing:

In[4]: help(Piku.get)

Which produces:

Help on built-in function get:

get(...)

D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.

Community
  • 1
  • 1
John
  • 6,433
  • 7
  • 47
  • 82
3

The exception is happening before it even gets into your isset function. When you do this:

isset(Piko['Name'])

… it's basically the same as doing this:

_tmp = Piko['Name']
isset(_tmp)

No matter what code you put inside isset, it's not going to help, because that function never gets called. The only place you can put the exception handling is one level up, in the function that calls isset.

Or, alternatively, you can not try to lookup dict[key] to pass into isset, and pass the dict and the key as separate parameters:

def isset(d, key):
    try:
        print(d[key])
    except KeyError:
        print(None)

But at this point, you're just duplicating dict.get in a clumsier way. You can do this:

def isset(d, key):
    print(d.get(key, None))

… or just scrap isset and do this:

print(Piko.get('Name', None))

Or, since None is the default if you don't specify anything:

print(Piko.get('Name'))
abarnert
  • 354,177
  • 51
  • 601
  • 671