前面的啰啰嗦嗦:
字典是“键—值对”的无序可变序列,用{ }初始化。
字典的键不允许重复,可以为整数,复数字符串,元组等,但不能为列表、集合或字典。
字典初始化:
a = {} #创建空字典
b = dict() #创建空字典
c = dict(name = 'Dong',age = 20)
d = dict.fromkeys(['name','age']) #创建值为空的字典
print(a)
print(b)
print(c)
print(d)
{}
{}
{'age': 20, 'name': 'Dong'}
{'age': None, 'name': None}
访问字典的元素:
1、使用”键’访问字典的“值‘,若键不存在,则会报错
print(c['name']) #键存在
print(c['sex']) #键不存在
Dong
Traceback (most recent call last):
File "D:/pythonwork/teast.py", line 9, in <module>
print(c['sex'])
KeyError: 'sex'
2、使用字典对象的get()方法,键存在时将返回值,否则返回指定值,默认为None
print(c.get('name'))
print(c.get('sex'))
print(c.get('sex','ABC'))
Dong
None
ABC
字典遍历
使用字典对象items()方法可以返回字典的“键-值”对列表
c = dict(name = 'Dong',age = 20,sex='male')
for item in c.items():
print(item)
print('')
for key,value in c.items():
print(key,value)
('age', 20)
('name', 'Dong')
('sex', 'male')
('age', 20)
('name', 'Dong')
('sex', 'male')
使用字典对象的keys()方法可以返回字典的“键”列表
c = dict(name = 'Dong',age = 20,sex='male')
for key in c.keys():
print(key)
print('')
for key in c:
print(key)
age
name
sex
age
name
sex
使用字典对象的values()方法可以返回字典的“值”列表
c = dict(name = 'Dong',age = 20,sex='male')
for v in c.values():
print(v)
print('')
print(c.values())
20
Dong
male
[20, 'Dong', 'male']
字典元素的添加和修改
当以“键”为下标为字典中的元素赋值时,若键不存在,则添加新的键,并赋值,若存在,则修改其对应的值
c = dict(name = 'Dong',age = 20,sex='male')
print(c)
c['age']=21
print(c)
c['score']=90
print(c)
{'age': 20, 'name': 'Dong', 'sex': 'male'}
{'age': 21, 'name': 'Dong', 'sex': 'male'}
{'age': 21, 'score': 90, 'name': 'Dong', 'sex': 'male'}
使用字典对象update()方法将另一个字典的“键值对”添加到新字典中
(若存在相同的键,则值以另一个字典的值为准)
d ={'age':30,'score':92}
print(d)
c ={'name':'Dong','age': 20,'sex':'male'}
print(c)
d.update(c)
print(d)
{'age': 30, 'score': 92}
{'age': 20, 'name': 'Dong', 'sex': 'male'}
{'age': 20, 'score': 92, 'name': 'Dong', 'sex': 'male'}
字典元素删除
c ={'name':'Dong','age': 20,'sex':'male','score':95}
print(c)
c.pop('age') #删除指定元素
print(c)
del c['name'] #删除指定元素
print(c)
c.clear() #删除字典中所有元素
print(c)
del c #删除字典
{'age': 20, 'score': 95, 'name': 'Dong', 'sex': 'male'}
{'score': 95, 'name': 'Dong', 'sex': 'male'}
{'score': 95, 'sex': 'male'}
{}
import collections
a = dict()
a['a']=1
a['b']=2
a['c']=3
print(a)
print('')
b = collections.OrderedDict()
b['a']=1
b['b']=2
b['c']=3
print(b)
{'a': 1, 'c': 3, 'b': 2}
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
资料参考:《Python程序设计基础》董付国