字 典

字典是Python中唯一的映射类型。映射类型对象里哈希值和指向的对象是一对多的关系。

创建字典

>>> fdict = dict(([1,'a'],[2,'b']))
>>> fdict
{1: 'a', 2: 'b'}


给默认值
>>> ddict = {}.fromkeys(('x','y'),-1)
>>> ddict
{'y': -1, 'x': -1}
>>> edict = {}.fromkeys(('a','b'))
>>> edict
{'a': None, 'b': None}


遍历字典
>>> for key in fdict.keys():
	print 'key=%s,value=%s' % (key,fdict[key])

	
key=1,value=a
key=2,value=b


读元素:
>>> fdict[1]
'a'
>>> fdict[3]

Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    fdict[3]
KeyError: 3
>>> ddict['x]
      
SyntaxError: EOL while scanning string literal
>>> ddict['x']
-1



删除元素
>>> testDict = {}
>>> testDict[1] = 'abc'
>>> testDict['abc']=1
>>> testDict
{1: 'abc', 'abc': 1}
>>> testDict[1.23]=2.34
>>> testDict
{1: 'abc', 'abc': 1, 1.23: 2.34}
>>> del test[1.23]

Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    del test[1.23]
NameError: name 'test' is not defined
>>> del testDict[1.23]
>>> testDict
{1: 'abc', 'abc': 1}
>>> testDict.p

Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    testDict.p
AttributeError: 'dict' object has no attribute 'p'
>>> testDict.pop()

Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    testDict.pop()
TypeError: pop expected at least 1 arguments, got 0
>>> testDict.pop(1)#删除并返回1的值 
'abc'
>>> testDict
{'abc': 1}
>>> testDict[2]='2'
>>> testDict
{2: '2', 'abc': 1}
>>> testDict.clear()#清空字典
>>> testDict
{}


字典合并
a = dict(([1,'2'],[2,'c']))
b = dict(([3,3],[4,4]))
print a, b
print dict(a.items()+b.items())

{1: '2', 2: 'c', 3: 3, 4: 4}


test
a = [1,2,3]
b = ['d','e','f']
c = dict()

i = 0
for aa in a:
    c.update({aa:b[i]})
    i = i+1
print c

{1: 'd', 2: 'e', 3: 'f'}

你可能感兴趣的:(字 典)