Skip to main content
 首页 » 编程设计

python之如何在python中引用空字典值

2025年05月04日10wuhuacong

如果不是很明显,我是一个通过网络教程学习的新手。

我正在尝试循环遍历不同长度的字典,并将结果放入表格中。我想将“无”放入可能为空值的表中。

我正在尝试以下代码:

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]) 

我得到以下输出/错误:

['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 

如何在字典中引用空值?

谢谢!

请您参考如下方法:

使用get()。默认将返回一个 None

val = dict1[thing].get(2) 

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

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

这样,无论 key 是否存在,您都可以获得有效的“无”作为后备。

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