2.3.2 访问字典对象的数据

  字典中的每个元素表示一种映射关系或对应关系,根据提供的“键”作为下标就可以访问对应的“值”,如果字典中不存在这个“键”会抛出异常,例如:

 1 >>> adict = {'address': 'SDIBT', 'score': [98, 97], 'name': 'Dong', 'sex': 'male', 'age': 38}
 2 >>> 
 3 >>> adict['age']                 #指定的键存在,返回对应的值
 4 38
 5 >>> 
 6 >>> adict['nothing']             #指定的键不存在,抛出异常
 7 Traceback (most recent call last):
 8   File "<pyshell#286>", line 1, in <module>
 9     adict['nothing']             #指定的键不存在,抛出异常
10 KeyError: 'nothing'
11 >>> 
12 >>> 
13 >>> #作者又用了断言,后边会详细解释的
14 >>> 
15 >>> assert 'nothing' in adict,'Key "nothong" not in adict'
16 Traceback (most recent call last):
17   File "<pyshell#291>", line 1, in <module>
18     assert 'nothing' in adict,'Key "nothong" not in adict'
19 AssertionError: Key "nothong" not in adict
20 >>> 

  

  为了避免程序运行时引发异常而导致崩溃,在使用下标的方式访问字典元素是,最好能配合条件判断或者异常处理结构,例如:

 1 >>> adict = {'score': [98, 97], 'name': 'Dong', 'sex': 'male', 'age': 38}
 2 >>> 
 3 
 4 >>> if 'Age' in adict:       #首先判断字典中是否存在指定的“键”
 5     print(adict['Age'])
 6 else:
 7     print('Not Exists.')
 8 
 9     
10 Not Exists.
11 >>> 
12 
13 #使用异常处理结构
14 >>> try:
15     print(adict['address'])
16 except:
17     print('Not Exists.')
18 
19     
20 Not Exists.
21 >>> 
22 
23 
24 #上述方法虽然能够满足要求,但是代码显得非常啰嗦,更好的办法就是字典对象提供了一个get()方法用来返回指定“键”对应的“值”,更秒的是这个方法允许指定该键不存在是返回特定的“值”,例如
25 >>> adict
26 {'score': [98, 97], 'name': 'Dong', 'sex': 'male', 'age': 38}
27 >>> 
28 >>> adict.get('age')                     #如果字典中存在该“键”,则返回对应的“值”
29 38
30 >>> 
31 >>> adict.get('nothing','Not Exists.')   #指定的键不存在时返回指定的默认值
32 'Not Exists.'
33 >>> 
34 >>> 

  字典对象的 setdefault() 方法用于返回指定“键”对应的“值”,如果字典中不存在该“键”,就添加一个新元素并设置该“键”对应的“值”,例如:

 1 >>> adict
 2 {'score': [98, 97], 'name': 'Dong', 'sex': 'male', 'age': 38}
 3 >>> 
 4 >>> adict.setdefault('nothing','nothing')        #字典增加新元素
 5 'nothing'
 6 >>> 
 7 >>> adict
 8 {'score': [98, 97], 'name': 'Dong', 'nothing': 'nothing', 'sex': 'male', 'age': 38}
 9 >>> 
10 >>> adict.setdefault('age')
11 38
12 >>> 

  最后,当对字典对象进行迭代时,默认是遍历字典的“建”,这一点必须清醒地记在那资历。当然,可以使用字典对象的items()方法返回字典中的元素,即所有“键:值”对,字典对象的keys()方法返回所有“键”,values()方法返回所有“值”。例如

 1 >>> for item in adict.items():  #明确指定遍历字典的元素
 2     print(item)
 3 
 4     
 5 ('score', [98, 97])
 6 ('name', 'Dong')
 7 ('nothing', 'nothing')
 8 ('sex', 'male')
 9 ('age', 38)
10 >>> 
11 >>> 
12 >>> adict.items()
13 dict_items([('score', [98, 97]), ('name', 'Dong'), ('nothing', 'nothing'), ('sex', 'male'), ('age', 38)])
14 >>> 
15 >>> adict.keys()
16 dict_keys(['score', 'name', 'nothing', 'sex', 'age'])
17 >>> 
18 >>> adict.values()
19 dict_values([[98, 97], 'Dong', 'nothing', 'male', 38])
20 >>> 

  

  小提示:内置函数len()、max()、min()、sum()、sorted()以及成员测试运算符in也适用于字典对象,但默认是用作用字典的“键”。若想作用于元素,即“键:值”对,则需要使用字典对象的items()方法明确指定;若想作用于“值”,则需要使用values()明确指定。

原文地址:https://www.cnblogs.com/avention/p/8545205.html