字典,又称关联数组或哈希表,是另一种可变容器模型,可存储任意类型对象,如其他容器模型。
字典由键和对应值成对组成,每个键与值用冒号:隔开,每对用逗号分割,整体放在花括号{}中。
键必须独一无二,但值则不必。值可以取任何数据类型,但必须是不可变的,如字符串,数或元组。
dict = {'Alice': '2341', 'Beth': '9102'};
不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住。
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}; # dict['Name']的值为Manni
键必须不可变,所以可以用数,字符串或元组充当,所以用列表就不行。
dict = {['Name']: 'Zara', 'Age': 7}; # 运行时出错
1 访问字典里的值
把相应的键放入熟悉的方括弧。
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name']; # 输出:dict['Name']: Zara
print "dict['Age']: ", dict['Age']; # 输出:dict['Age']: 7
如果用字典里没有的键访问数据,会输出错误如下:
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
# 输出:dict['Zara']:
# Traceback (most recent call last):
# File "test.py", line 4, in <module>
# print "dict['Alice']: ", dict['Alice'];
# KeyError: 'Alice'
2 修改字典
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']; # 输出:dict['Age']: 8
print "dict['School']: ", dict['School']; # 输出:dict['School']: DPS School
3 删除字典元素
能删单一的元素,也能清空字典,清空只需一项操作。显示删除一个字典用del命令。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # 删除键是'Name'的条目
dict.clear(); # 清空词典所有条目
del dict ; # 删除词典
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
但这会引发一个异常,因为用del后字典不再存在。
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
4 字典内置函数和方法
4.1 字典内置函数
序号 | 函数及描述 |
---|---|
1 | cmp(dict1, dict2) 比较两个字典元素。如果两个字典的元素相同返回0,如果字典dict1大于字典dict2返回1,如果字典dict1小于字典dict2返回-1。 |
2 | len(dict) 计算字典元素个数,即键的总数。 |
3 | str(dict) 输出字典可打印的字符串表示。 |
4 | type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。 |
序号 | 函数及描述 |
---|---|
1 | dict.clear() 删除字典内所有元素。 |
2 | dict.copy() 返回一个字典的浅复制。 |
3 | dict.fromkeys(seq[, value])) 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值。 |
4 | dict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值。 |
5 | dict.has_key(key) 如果键在字典dict里返回true,否则返回false。 |
6 | dict.items() 以列表返回可遍历的(键, 值) 元组数组。 |
7 | dict.keys() 以列表返回一个字典所有的键。 |
8 | dict.setdefault(key, default=None) 和get()类似,,但如果键不已经存在于字典中,将会添加键并将值设为default。 |
9 | dict.update(dict2) 把字典dict2的键/值对更新到dict里。 |
10 | dict.values() 以列表返回字典中的所有值。 |
Done.