Python:dict学习笔记
Posted La La Land
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python:dict学习笔记相关的知识,希望对你有一定的参考价值。
dict全称dictionary,使用键-值(key-value)存储,有极快的查找速度。
以下整理几种常用的dict用法
定义
>>> dict={} >>> dict={‘adele‘:‘hello‘,‘taylor‘:‘1989‘} >>> dict {‘taylor‘: ‘1989‘, ‘adele‘: ‘hello‘}
嵌套
>>> a_dict={1:"{11:‘a‘,12:‘b‘}",2:"2B",3:"3C"} >>> a_dict {1: "{11:‘a‘,12:‘b‘}", 2: ‘2B‘, 3: ‘3C‘} >>> a_dict[1][12] ‘b‘
获取键、值
>>> a_dict.keys() [1, 2, 3] #结果为list >>> a_dict.values() ["{11:‘a‘,12:‘b‘}", ‘2B‘, ‘3C‘] >>> a_dict.items() [(1, "{11:‘a‘,12:‘b‘}"), (2, ‘2B‘), (3, ‘3C‘)] #结果为list,list里面的元素是元组 >>> for key in a_dict: ... print (key) ... 1 2 3 >>> for value in a_dict.values(): ... print(value) ... {11:‘a‘,12:‘b‘} 2B 3C >>> for key in a_dict: ... print a_dict[key] ... {11:‘a‘,12:‘b‘} 2B 3C >>> for k,v in a_dict.items(): ... print str(k)+":"+str(v) ... 1:{11:‘a‘,12:‘b‘} 2:2B 3:3C >>> for k in a_dict: ... print str(k)+":"+str(a_dict[k]) ... 1:{11:‘a‘,12:‘b‘} 2:2B 3:3C >>> for k in a_dict: ... print "a_dict(%s)="%k,a_dict[k] ... a_dict(1)= {11:‘a‘,12:‘b‘} a_dict(2)= 2B a_dict(3)= 3C >>> a_dict.get(1) "{11:‘a‘,12:‘b‘}"
删除
>>> a_dict.pop(‘taylor‘) ‘1989‘ #根据键值删除,并返回值 >>> del a_dict[1] >>> a_dict {2: ‘2B‘, 3: ‘3C‘, ‘adele‘: ‘hello‘} >>> a_dict.clear() >>> a_dict {}
拷贝
>>> new_dict=a_dict.copy() >>> new_dict {1: "{11:‘a‘,12:‘b‘}", 2: ‘2B‘, 3: ‘3C‘}
合并
>>> add_dict={‘adele‘:‘hello‘,‘taylor‘:‘1989‘} >>> a_dict.update(add_dict) >>> a_dict {1: "{11:‘a‘,12:‘b‘}", 2: ‘2B‘, 3: ‘3C‘, ‘adele‘: ‘hello‘, ‘taylor‘: ‘1989‘}
排序
>>> print sorted(a_dict.items(),key=lambda d:d[0]) [(1, "{11:‘a‘,12:‘b‘}"), (2, ‘2B‘), (3, ‘3C‘)] #按照key排序 >>> print sorted(a_dict.items(),key=lambda d:d[1]) [(2, ‘2B‘), (3, ‘3C‘), (1, "{11:‘a‘,12:‘b‘}")] #按照value排序
后续使用中,再补充..
以上是关于Python:dict学习笔记的主要内容,如果未能解决你的问题,请参考以下文章