{字典}【比元组方便(元组不可变);比列表方便(列表无法实现存储数据的映射关系)】【一一映射】
用列表时:
t=[name='mike',age=30] #failed
t[0] #不能直观地知道取的是什么
- 字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息。
- 字典是python中唯一的映射类型(哈希表)
- 字典是对象是可变的(列表也是),但字典的键必须使用不可变对象。
- keys()返回键列表;values()返回值列表;
A.创建字典
dic1={'name':'mike','age':30,'gender':'male'}
B.引用
dic1['name']
C.访问字典的值
遍历的方法
用for循环
I.
for k in dic1:
print k #print the key#
II.
for k in dic1:
print dic[k] #print the value#
D.更新与删除
添加:
dic['tel']='456789'
注意添加新值后,不一定跟在其末尾。字典的无序性(哈希表)
修改:直接改,利用key值。
dic['tel']=''7777777'
删除:del()
del(dic['tel'])
dic1.pop('tel') #both delete the tel#
del dic1 #delete the whole dictionary#
dic1.clear() #delete the content of the dictionary,but the dictionary remains#
E.字典的内建函数
type()
str()
cmp()
工厂函数dict( )
dict.get() get取相应的key;从字典中取相应的key;若字典有,则返回;若无则自定义无,不报错。
dict.get(5,'error')
若key值为5的值不存在,则返回error.
dict.items() 使用字典中的每个键/值对,这会返回一个元组的列表,其中每个元组都包含一对项目
1.注意缩进--注意冒号
2.多分支 if:
elif:
else:
3.for循环
常用于:A.遍历序列
for i in 序列(list/string/tupple/equal):
#代码块#
B.迭代序列指数(索引)【range】
fruits=['banna','apple','mango']
for index in range(len(fruits)):
print 'Current fruit:',fruits[index]
print 'Goodbye!'
range(i,j,步长)
如果所创建的对象为整数,可以用range;
i为初始数值,不选默认为0;
j为终止数值,但不包括在范围内;步长为可选参数,不选则默认为1;
range不管用不用,都生成,较占内存。
与xrange()对比。
for...else...
在python中,当for循环正常结束,执行else模块
当for非正常结束,则不执行else模块。
非正常结束:1.执行break语句;2.在执行的过程中遇到ctrl+c等。
4.遍历
遍历有两种方法:A.通过取元素的方法 B.通过序列本身的偏移进行遍历
字符串:
s='hello'
for x in range(len(s)):
print s[x]
字典:
方法一:
d={1:111,2:222,3:333}
d.item() #get both keys and values#
方法二:
for x in d:
print x #get the key#
for x in d:
print d[x] #get the value#
for x in d:
print d.items(x) #get the pair#