一、字典介绍
1.字典概述
①字典是python中唯一内建的映射类型。又称关联数组或散列
②映射类型对象里哈希值(键,key)和指向的对象(值,value)是一对多的的关系,通常被认为是可变的哈希表
③字典对象是可变的,它是一个容器类型,能存储任意个数的Python对象,其中也可包括其他容器类型。
④字典通过键实现元素存取,可变类型容器,长度可变,异构,嵌套
2.字典类型与序列类型的区别:
①存取和访问数据的方式不同。
②序列类型只用数字类型的键(从序列的开始按数值顺序索引);
③映射类型可以用其他对象类型作键(如:数字、字符串、元祖,一般用字符串作键),和序列类型的键不同,映射类型的键直接或间接地和存储数据值相关联。
④映射类型中的数据是无序排列的。这和序列类型是不一样的,序列类型是以数值序排列的。
⑤映射类型用键直接“映射”到值。
二、字典的基本操作
1、创建字典
{key1:value1,key2:value2, .....}
{} 表示空字典
{‘x’:32,‘y’:[1,2,3]}
特点:
1、键与值用冒号“:”分开;
2、项与项用逗号“,”分开;
3、字典中的键必须是唯一的,而值可以不唯一。
建议:
如果字典中的值为数字,最好使用字符串数字形式,如:'age':'26′ 而不用 ‘age':26
2、如何访问字典中的值?
dict[key] 形式返回键key对应的值value,如果key不在字典中会引发一个KeyError。
dict={'x':32,'y':[1,2,3,4,]}
result=dict['x'] #取值的时候按键key取值
print(result)
输出32
dict={'x':32,'y':[1,2,3,4,]}
result=dict['y'][3:] #按键key取值,里面列表索引为3的值
print(result)
输出4
3、如何检查key是否在字典中?
①has_key()方法 形如:dict.haskey(‘name') 有–>True,无–>False
②in 、not in 形如:'name' in dict 有–>True,无–>False
4、如何更新字典?
①添加一个数据项(新元素)或键值对
dict[new_key] = value 形式添加一个项
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['sex'] = 'female'
print(dict)
输出{'Name': 'Zara', 'Age': 7, 'Class': 'First', 'sex': 'female'}
②更新一个数据项(元素)或键值对
dict[old_key] = new_value
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8
dict['School'] = "DPS School"
print(dict['Age'],dict['School'])
print(dict)
输出
8 DPS School
{'Name': 'Zara', 'Age': 8, 'Class': 'First', 'School': 'DPS School'}
③删除一个数据项(元素)或键值对
del dict[key] 删除键key的项 / del dict 删除整个字典
del dict 删除字典
dict.pop(key) 删除键key的项并返回key对应的 value值
dict.clear() 清空字典所有条目
四、映射类型操作符
标准类型操作符(+,-,*,<,>,<=,>=,==,!=,and,or, not)
a、字典不支持拼接和重复操作符(+,*)
b、字典的比较操作
先比较字典的长度也就是字典的元素个数
键比较
值比较
1、len() 计算字典元素个数,即键的总数
2、hash() 返回对象的哈希值,可以用来判断一个对象能否用来作为字典的键
3、dict() 工厂函数,用来创建字典
4、cmp(dict1, dict2):比较两个字典元素
5、str(dict):输出字典可打印的字符串表示
6、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型
六、字典的方法
class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) """ def clear(self): # real signature unknown; restored from __doc__ """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(*args, **kwargs): # real signature unknown """ Returns a new dict with keys from iterable and values equal to value. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def items(self): # real signature unknown; restored from __doc__ """ D.items() -> a set-like object providing a view on D's items """ pass def keys(self): # real signature unknown; restored from __doc__ """ D.keys() -> a set-like object providing a view on D's keys """ pass def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ D.values() -> an object providing a view on D's values """ pass def __contains__(self, *args, **kwargs): # real signature unknown """ True if D has a key k, else False. """ pass def __delitem__(self, *args, **kwargs): # real signature unknown """ Delete self[key]. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) # (copied from class doc) """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __setitem__(self, *args, **kwargs): # real signature unknown """ Set self[key] to value. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None