今天来总结下python3.4版本字典的一些操作方法。
字典是Python里面一种无序存储结构,存储的是键值对 key - value。关键字应该为不可变类型,如字符串、整数、包含不可变对象的元组。字典的创建很简单,
用 d = {key1 : value2, key2 : value2}的形式就可以创建一个新的字典,当然也可以通过 dict 接受一个含有键,值的序列对或者关键字参数来创建字典。
键可以是多种类型,但键是唯一的不重复的,值可以不唯一
字典:
1、in语句,判断一个元素(键)是否在一个字典里
2、not 语句表示对后面的否定
3、len 可以检测字典的元素个数
4、max 可以返回最大元素,min 返回最小元素
5、len(dict)返回dict的长度
6、del dict[key]删除字典dict中键为key的元素,如果key不存在,则引起KeyError类型错误
字典方法:
1、d.clear() 清空字典d
2、d.copy() 对字典 d 进行浅复制,返回一个和d有相同键值对的新字典
3、d.get( x [ , y]) 返回字典 d 中键 x 对应的值,键 x 不存在的时候返回 y, y 的默认值为None
4、d.items() 将字典 d 中所有键值对以dict_items的形式返回(Python 2中d.iteritems() 返回一个针对键值对的迭代器对象,Python 3中没有 iteritems 方法了)
5、d.pop( x[, default]) ) 返回给定键 x 对应的值,并将该键值对从字典中删除,如果x不在字典d,则返回default;若x既不在d中,同时default未设置,则引起KeyError类型错误
6、d.popitem( ) 返回并删除字典 d 中随机的键值对
7、d.setdefault( x, [ , y ] ) 返回字典 d 中键 x 对应的值,若键 x 不存在,则返回 y, 并将 x : y 作为键值对添加到字典中,y 的默认值为 None
8、d.update( x ) 将字典 x 所有键值对添加到字典 d 中(不重复,重复的键值对用字典 x 中的键值对替代字典 d 中)
9、d.keys() 将字典 d 中所有的键以dict_keys形式返回一个针对键的迭代器对象
10、d.values( ) 将字典里所有的值以dict_values 的形式返回针对字典d里所有值的迭代器对象
11、d.fromkeys(iterable, value=None)返回一个新的字典,键来自iterable,value为键值
1 >>> d = {'a':1, 'b':2} 2 >>> d 3 {'b': 2, 'a': 1} 4 >>> L = [('Jonh',18), ('Nancy',19)] 5 >>> d = dict(L) #通过包含键值的列表创建 6 >>> d 7 {'Jonh': 18, 'Nancy': 19} 8 >>> T = tuple(L) 9 >>> T 10 (('Jonh', 18), ('Nancy', 19)) 11 >>> d = dict(T) #通过包含键值的元组创建 12 >>> d 13 {'Jonh': 18, 'Nancy': 19} 14 >>> d = dict(x = 1, y = 3) #通过关键字参数创建 15 >>> d 16 {'x': 1, 'y': 3} 17 >>> d[3] = 'z' 18 >>> d 19 {3: 'z', 'x': 1, 'y': 3} 20 21 22 >>> d 23 {3: 'z', 'y': 3} 24 >>> L1 = [1,2,3] 25 >>> d.fromkeys(L1) 26 {1: None, 2: None, 3: None} 27 >>> {}.fromkeys(L1,'nothing') 28 {1: 'nothing', 2: 'nothing', 3: 'nothing'} 29 >>> dict.fromkeys(L1,'over') 30 {1: 'over', 2: 'over', 3: 'over'} 31 32 33 >>> d 34 {3: 'z', 'x': 1, 'y': 3} 35 >>> d[3] 36 'z' 37 >>> d['x'] 38 1 39 >>> d[0] 40 Traceback (most recent call last): 41 File "<pyshell#26>", line 1, in <module> 42 d[0] 43 KeyError: 0 44 45 46 >>> d = {'z': 5, 'x': 1.5, 'y': 3} 47 >>> d.items() 48 dict_items([('z', 5), ('x', 1.5), ('y', 3)]) 49 >>> list(d.items()) 50 [('z', 5), ('x', 1.5), ('y', 3)] 51 52 >>> d.keys() 53 dict_keys(['z', 'x', 'y']) 54 >>> for x in d.keys(): 55 print(x) 56 z 57 x 58 y 59 60 >>> d1 = {'x':1, 'y':3} 61 >>> d2 = {'x':2, 'z':1.4} 62 >>> d1.update(d2) 63 >>> d1 64 {'z': 1.4, 'x': 2, 'y': 3} 65 66 >>> d1 67 {'z': 1.4, 'x': 2, 'y': 3} 68 >>> d1.values() 69 dict_values([1.4, 2, 3]) 70 >>> list(d1.values()) 71 [1.4, 2, 3]