字典 公共方法
字典介绍
想一想:
如果有列表
nameList = ['xiaoZhang', 'xiaoWang', 'xiaoLi'];
需要对"xiaoWang"这个名字写错了,通过代码修改:
nameList[1] = 'xiaoxiaoWang'
如果列表的顺序发生了变化,如下
nameList = ['xiaoWang', 'xiaoZhang', 'xiaoLi'];
此时就需要修改下标,才能完成名字的修改
nameList[0] = 'xiaoxiaoWang'
有没有方法,既能存储多个数据,还能在访问元素的很方便就能够定位到需要的那个元素呢?
答:
字典
另一个场景:
学生信息列表,每个学生信息包括学号、姓名、年龄等,如何从中找到某个学生的信息?
>>> studens = [[1001, "王bao强", 24], [1002, "马rong", 23], [1005,
<1>生活中的字典
<2>软件开发中的字典
info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}
说明:
字典和列表一样,也能够存储多个数据
列表中找某个元素时,是根据下标进行的
字典中找某个元素时,是根据’名字’(就是冒号:前面的那个值,例如上面代码中的’name’、‘id’、‘sex’)
字典的每个元素由2部分组成,键:值。例如 ‘name’:‘班长’ ,'name’为键,'班长’为值
<3>根据键访问值
info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}
print(info['name'])
print(info['address'])
结果:
班长
地球亚洲中国北京
若访问不存在的键,则会报错:
>>> info['age']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'age'
在我们不确定字典中是否存在某个键而又想获取其值时,可以使用get方法,还可以设置默认值:
>>> age = info.get('age')
>>> age #'age'键不存在,所以age为None
>>> type(age)
<type 'NoneType'>
>>> age = info.get('age', 18) # 若info中不存在'age'这个键,就返回默认值18
>>> age
18
字典的常见操作1
<1>修改元素
字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改
demo:
info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}
new_id = input('请输入新的学号:')
info['id'] = int(new_id)
print('修改之后的id为: %d' % info['id'])
结果:
<2>添加元素
demo: 访问不存在的元素
info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
print('id为:%d' % info['id'])
结果:
>>> info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
>>>
>>> print('id为:%d' % info['id'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'id'
如果在使用 变量名[‘键’] = 数据 时,这个“键”在字典中,不存在,那么就会新增这个元素。
demo: 添加新的元素
info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
#print('id为:%d'%info['id'])#程序会终端运行,因为访问了不存在的键
newId = input('请输入新的学号:')
info['id'] = newId
print('添加之后的id为:%d' % info['id'])
结果:
请输入新的学号:188
添加之后的id为: 188
<3>删除元素
对字典进行删除操作,有一下几种:
del
clear()
demo: del删除指定的元素
info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
print('删除前,%s' % info['name'])
del info['name']
print('删除后,%s' % info['name'])
结果
>>> info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}
>>>
>>> print('删除前,%s' % info['name'])
删除前,班长
>>>
>>> del info['name']
>>>
>>> print('删除后,%s' % info['name'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'name'
demo: del删除整个字典
info = {'name':'monitor', 'sex':'f', 'address':'China'}
print('删除前,%s' % info)
del info
print('删除后,%s' % info)
结果
demo: clear清空整个字典
info = {'name':'monitor', 'sex':'f', 'address':'China'}
print('清空前,%s' % info)
info.clear()
print('清空后,%s' % info)
结果
字典的常见操作2
<1>len()
测量字典中,键值对的个数
dict01 = {'name': '张三', 'age': 18, 'sex': 'm'}
print(len(dict01)) #3
<2>keys
返回一个包含字典所有KEY的列表
dict01 = {'name': '张三', 'age': 18, 'sex': 'm'}
keys = dict01.keys()
print(keys) # ['name', 'age', 'sex']
<3>values
返回一个包含字典所有value的列表
dict01 = {'name': '张三', 'age': 18, 'sex': 'm'}
values = dict01.values()
print(values) # ['张三', 18, 'm']
<4>items
返回一个包含所有(键,值)元祖的列表
dict01 = {'name': '张三', 'age': 18, 'sex': 'm'}
items = dict01.items()
print(items) # [('name', '张三'), ('age', 18), ('sex', 'm')]
<5>has_key (Python3 已取消,了解即可)
dict.has_key(key)如果key在字典中,返回True,否则返回False,注意用python2运行
-*- coding:utf-8 -*—
dict01 = {'name': '张三', 'age': 18, 'sex': 'm'}
dict01.has_key('name') # True
遍历
通过for … in … 我们可以遍历字符串、列表、元组、字典等
注意python语法的缩进
字符串遍历
>>> a_str = "hello itcast"
>>> for char in a_str:
... print(char,end=' ')
...
h e l l o i t c a s t
列表遍历
>>> a_list = [1, 2, 3, 4, 5]
>>> for num in a_list:
... print(num,end=' ')
...
1 2 3 4 5
元组遍历
>>> a_turple = (1, 2, 3, 4, 5)
>>> for num in a_turple:
... print(num,end=" ")
1 2 3 4 5
字典遍历
<1> 遍历字典的key(键)
dict01 = {'name': '张三', 'age': 18, 'sex': 'm'}
for key in dict01.keys():
print(key)
结果:
name
age
sex
<2> 遍历字典的value(值)
dict01 = {'name': '张三', 'age': 18, 'sex': 'm'}
for value in dict01.values():
print(value)
结果:
张三
18
m
<3> 遍历字典的项(元素)
dict01 = {'name': '张三', 'age': 18, 'sex': 'm'}
for item in dict01.items():
print(item)
结果:
('name', '张三')
('age', 18)
('sex', 'm')
<4> 遍历字典的key-value(键值对)
dict01 = {'name': '张三', 'age': 18, 'sex': 'm'}
for key, value in dict01.items():
print('%s--%s' % (key, value))
结果:
name--张三
age--18
sex--m
想一想,如何实现带下标索引的遍历
>>> chars = ['a', 'b', 'c', 'd']
>>> i = 0
>>> for chr in chars:
... print("%d %s"%(i, chr))
... i += 1
...
0 a
1 b
2 c
3 d
enumerate()
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
>>> chars = ['a', 'b', 'c', 'd']
>>> for i, chr in enumerate(chars):
... print("%d %s"%(i, chr))
...
0 a
1 b
2 c
3 d
公共方法
.+
>>> "hello " + "itcast"
'hello itcast'
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> ('a', 'b') + ('c', 'd')
('a', 'b', 'c', 'd')
.*
>>> 'ab' * 4
'ababab'
>>> [1, 2] * 4
[1, 2, 1, 2, 1, 2, 1, 2]
>>> ('a', 'b') * 4
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')
in
>>> 'itc' in 'hello itcast'
True
>>> 3 in [1, 2]
False
>>> 4 in (1, 2, 3, 4)
True
>>> "name" in {"name":"Delron", "age":24}
True
注意,in在对字典操作时,判断的是字典的键
python内置函数
Python包含了以下内置函数
序号 方法 描述
1 cmp(item1, item2) 比较两个值
2 len(item) 计算容器中元素个数
3 max(item) 返回容器中元素最大值
4 min(item) 返回容器中元素最小值
5 del(item) 删除变量
cmp
>>> cmp("hello", "itcast")
-1
>>> cmp("itcast", "hello")
1
>>> cmp("itcast", "itcast")
0
>>> cmp([1, 2], [3, 4])
-1
>>> cmp([1, 2], [1, 1])
1
>>> cmp([1, 2], [1, 2, 3])
-1
>>> cmp({"a":1}, {"b":1})
-1
>>> cmp({"a":2}, {"a":1})
1
>>> cmp({"a":2}, {"a":2, "b":1})
-1
注意:cmp在比较字典数据时,先比较键,再比较值。
len
>>> len("hello itcast")
12
>>> len([1, 2, 3, 4])
4
>>> len((3,4))
2
>>> len({"a":1, "b":2})
2
注意:len在操作字典数据时,返回的是键值对个数。
max
>>> max("hello itcast")
't'
>>> max([1,4,522,3,4])
522
>>> max({"a":1, "b":2})
'b'
>>> max({"a":10, "b":2})
'b'
>>> max({"c":10, "b":2})
'c'
del
del有两种用法,一种是del加空格,另一种是del()
>>> a = 1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> a = ['a', 'b']
>>> del a[0]
>>> a
['b']
>>> del(a)
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
多维列表/元祖访问的示例
>>> tuple1 = [(2,3),(4,5)]
>>> tuple1[0]
(2, 3)
>>> tuple1[0][0]
2
>>> tuple1[0][2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> tuple1[0][1]
3
>>> tuple1[2][2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> tuple2 = tuple1+[(3)]
>>> tuple2
[(2, 3), (4, 5), 3]
>>> tuple2[2]
3
>>> tuple2[2][0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable