DBWeinstein
DBWeinstein

Reputation: 9549

how to refer to empty dict value in python

If not immediately obvious, i'm a newbie learning via net tutorials.

I'm trying to loop through a dict of dicts with varying lengths, and put the results in a table. I'd like to put'nothing' into the table where an empty value might be.

I'm trying the following code:

import os

os.system("clear")

dict1 = {'foo': {0:'a', 1:'b', 3:'c'}, 'bar': {0:'l', 1:'m', 2:'n'}, 'baz': {0:'x', 1:'y'} }
list1 = []
list2 = []
list3 = []

for thing in dict1:
    list1.append(dict1[thing][0])
print list1

for thing in dict1:
    list2.append(dict1[thing][1])
print list2

for thing in dict1:
    if dict1[thing][2] == None:
        list3.append('Nothing')
    else:
        list3.append(dict1[thing][2])

and I get the following output/error:

['x', 'a', 'l']
['y', 'b', 'm']
Traceback (most recent call last):
  File "county.py", line 19, in <module>
    if dict1[thing][2] == None:
KeyError: 2

How do I refer to an empty value in a dict?

Thanks!

Upvotes: 1

Views: 3761

Answers (3)

RobL
RobL

Reputation: 1

Trying to access a key that doesn't exist using the [] operator will always return a KeyError. You can either use the dict.get(key, default) method to return the value specified in the default parameter, or you can but the dictionary accessing in a try/except block, and have the except block catch the KeyError exception and append 'Nothing' to the list instead.

Upvotes: 0

Platinum Azure
Platinum Azure

Reputation: 46233

You should be using the in or not in operator to check for key presence:

if 2 not in dict[thing]:
    # do something

Or if you really want None as a fallback, use .get():

val = dict[thing].get(2)
if val is None:
    # do something

Also, in the future, you should be using is None when comparing to None.

Upvotes: 5

jdi
jdi

Reputation: 92647

Use get(). The default will return a None

val = dict1[thing].get(2)

Or to specify what you want the default to be:

val = dict1[thing].get(2, 'nothing')

This way, regardless of whether the key exists, you will be able to get your valid "nothing" as a fallback.

for thing in dict1:
    list3.append(dict1[thing].get(2, 'Nothing'))

Upvotes: 6

Related Questions