如何在python中引用空的dict值

dws*_*ein 1 python dictionary

如果没有立即明显,我通过网络教程学习新手.

我试图通过不同长度的词典来循环,并将结果放在一个表格中.我想把"没什么"放到可能有空值的表中.

我正在尝试以下代码:

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])
Run Code Online (Sandbox Code Playgroud)

我得到以下输出/错误:

['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
Run Code Online (Sandbox Code Playgroud)

如何在dict中引用空值?

谢谢!

jdi*_*jdi 5

使用get().默认将返回aNone

val = dict1[thing].get(2)
Run Code Online (Sandbox Code Playgroud)

或者指定您想要的默认值:

val = dict1[thing].get(2, 'nothing')
Run Code Online (Sandbox Code Playgroud)

这样,无论密钥是否存在,您都可以获得有效的"无"作为后备.

for thing in dict1:
    list3.append(dict1[thing].get(2, 'Nothing'))
Run Code Online (Sandbox Code Playgroud)


Pla*_*ure 5

您应该使用innot in运算符来检查密钥存在:

if 2 not in dict[thing]:
    # do something
Run Code Online (Sandbox Code Playgroud)

或者,如果您真的想要None作为后备,请使用.get():

val = dict[thing].get(2)
if val is None:
    # do something
Run Code Online (Sandbox Code Playgroud)

此外,在将来,您应该is None在比较时使用None.