首页 > 代码库 > python字典

python字典

定义:

>>> dic={1:‘a‘,2:‘b‘}
>>> dic
{1: ‘a‘, 2: ‘b‘}

 

>>> dic=dict(([3,"x"],[4,"y"]))
>>> dic
{3: ‘x‘, 4: ‘y‘}

 

字典key是唯一的

 

字典是可变类型

 

字典是无序的类型

 

>>> dic={1:"a",2:"b",3:"c",4:"d"}
>>> for i in dic:
... print i
...
1
2
3
4

 

访问:

>>> dic={1:"a",2:"b",3:"c",4:"d"}
>>> dic[1]
‘a‘
>>> dic[3]
‘c‘

 

 

删除:

>>> dic={1:"a",2:"b",3:"c",4:"d"}

>>> dic.pop(1)
‘a‘
>>> dic
{2: ‘b‘, 3: ‘c‘, 4: ‘d‘}

>>> del dic[2]
>>> dic
{3: ‘c‘, 4: ‘d‘}

>>> dic.clear()
>>> dic
{}

 

del可以把这个数据对象给删掉,删除一次引用计数

真正释放数据内存的时候 是这个引用计数为0的时候

 

返回一个键值对:

>>> dic={1:"a",2:"b",3:"c",4:"d"}
>>> dic.popitem()
(1, ‘a‘)
>>> dic.popitem()
(2, ‘b‘)

>>> dic
{3: ‘c‘, 4: ‘d‘}

 

keys()  values()   items() :

>>> dic={1:"a",2:"b",3:"c",4:"d"}
>>> dic.keys()
[1, 2, 3, 4]
>>> dic.values()
[‘a‘, ‘b‘, ‘c‘, ‘d‘]
>>> dic.items()
[(1, ‘a‘), (2, ‘b‘), (3, ‘c‘), (4, ‘d‘)]

 

in 判断字典中的某个key是否存在:

>>> 1 in dic
True
>>> 5 in dic
False

 

python字典