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!
Use
get(). The default will return aNoneOr to specify what you want the default to be:
This way, regardless of whether the key exists, you will be able to get your valid “nothing” as a fallback.