Dictionary
键key:拼音值value:页码key-value:键值对字典是python中唯一的映射类型,指两个元素之间一一对应的关系(注明:字典是映射类型,不是序列类型)brand=[‘外星人‘,‘戴尔’,‘联想’,‘苹果’]English=[‘AlienWare‘,‘Dell‘,‘Lenovo‘,‘Apple‘]#品牌与英文一一对应print(‘外星人---‘,‘AlienWare‘)显示不出来中文,ASCII是十进制, 此时utf-8用的是Unicode,对应的是十六进制的数据,此时转换过程#不行,byteString,十进制,unicodeString 十六进制,python2默认十进制,
• Creation of dictionaries in Access
dict:字典可以dict(),n内置方法d={}表示形式d={‘外星人‘:‘AlienWare‘,‘戴尔‘:‘Dell‘,‘联想‘:‘Lenovo‘,‘苹果‘:‘Apple‘}print d[‘外星人‘]AlienWare
1. Name ={Key 1: value 1, key 2: Value 2, ... }
2. Empty Dictionary ={}
3. Create a dictionary with functions
Dict (mapping)
d=dict(((‘one‘,1),(‘two‘,2),(‘three‘,3)))#可以用列表 只要映射关系正确都可以print d#{‘three‘: 3, ‘two‘: 2, ‘one‘: 1}
4. Create a dictionary with keyword parameters
d=dict(one=1,two=2,three=3)print d#{‘three‘: 3, ‘two‘: 2, ‘one‘: 1}
• Access to Dictionaries
1. Name of dictionary [key name]
2, rewrite the value of the key corresponding
d=dict(one=1,two=2,three=3)d[‘one‘]=100print d#{‘three‘: 3, ‘two‘: 2, ‘one‘: 100}3、增加新的键值对d[‘four‘]=4print d#{‘four‘: 4, ‘three‘: 3, ‘two‘: 2, ‘one‘: 100}4、访问不存在的键值对: 报错 ·字典的内键方法(内置函数):1、fromkeys(...) 创建并且返回一个新的字典 dict.fromkeys(s,[,v]) s:键 v:值(没有给值,默认None)当第一个参数是容器(元祖,列表,字典)时,会将第二个参数的整体看成键的值d.fromkeys((‘one‘,‘two‘,‘three‘))#{‘three‘: None, ‘two‘: None, ‘one‘: None}d.fromkeys([‘one‘,‘two‘,‘three‘])#{‘three‘: None, ‘two‘: None, ‘one‘: None}d.fromkeys({‘one‘:1,‘two‘:2,‘three‘:3})#{‘one‘: None, ‘three‘: None, ‘two‘: None}只拿键不拿值d.fromkeys([‘one‘,‘two‘,‘three‘],[1,2,3])#{‘three‘: [1, 2, 3], ‘two‘: [1, 2, 3], ‘one‘: [1, 2, 3]}
2. Keys ()
Returns a reference to a dictionary key
d=d.fromkeys([‘one‘,‘two‘,‘three‘]) d.keys()#[‘three‘, ‘two‘, ‘one‘](把所有键拿出了封装列表输出)3、values()d={‘one‘:1,‘two‘:2,‘three‘:3}d.values()#[3, 2, 1] 返回字典中的值引用(把所有值拿出了,封装一个列表返回)
4. Items ()
d.items()#[(‘three‘, 3), (‘two‘, 2), (‘one‘, 1)]返回字典的项(键值对)
5. Get (Key[,d])
Get (Access) a key value pair in a dictionary
d.get(‘one‘)#1 d.get(‘five‘) print d.get(‘five‘)#None
6, In/not in
d={‘one‘:1,‘two‘:2,‘three‘:3}‘three‘in d#True‘five‘in d #False
7. Clear ()
Empty dictionary
d.clear()d#{}
8. Copy ()
浅拷贝字典拷贝,地址不同 开始字典里面内容没有发生改变,更深地址不变。
9. Pop ()
The given key pops up the corresponding key-value pair (the popup value is removed in the dictionary with no corresponding key
, and the dictionary does not have an exception, it will error. ) returns the corresponding value.
{‘three‘: 3, ‘two‘: 2, ‘one‘: 1}d.pop(‘one‘)#1
10, Popitem ()
同上,返回是一个键值对(栈空间)。d={‘three‘: 3, ‘two‘: 2, ‘one‘: 1}d.popitem()#(‘one‘, 1)弹出是随机的 内存上面的
11, SetDefault (...)
If there is no key-value pair in the dictionary, a key is created at random location, and if the value is not set, the default is None
setdefault(k,[,d])d={‘three‘: 3, ‘two‘: 2}d.setdefault(‘one‘)d#{‘one‘: None, ‘three‘: 3, ‘two‘: 2}
12, using dictionary mapping relationship, update the dictionary
d={‘three‘: 3, ‘two‘: 2, ‘one‘: 1}a={‘three‘:5}d.update(a)d#{‘one‘: 1, ‘three‘: 5, ‘two‘: 2}
python-010-Dictionary