字典是另一种可变容器模型,且可存储任意类型对象,如其他容器模型。
字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}也可如此创建字典:
dict1 = { 'abc': 456 }; dict2 = { 'abc': 123, 98.6: 37 };每个键与值用冒号隔开(:),每对用逗号,每对用逗号分割,整体放在花括号中({})。
键必须独一无二,但值则不必。
值可以取任何数据类型,但必须是不可变的,如字符串,数或元组。
把相应的键放入熟悉的方括弧,如下实例:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print "dict['Name']: ", dict['Name']; print "dict['Age']: ", dict['Age'];以上实例输出结果:
dict['Name']: Zara 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'
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:
#!/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']; print "dict['School']: ", dict['School'];以上实例输出结果:
dict['Age']: 8 dict['School']: DPS School
能删单一的元素也能清空字典,清空只需一项操作。
显示删除一个字典用del命令,如下实例:
#!/usr/bin/python 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
注:del()方法后面也会讨论。
字典键的特性
字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。
两个重要的点需要记住:
1、不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}; print "dict['Name']: ", dict['Name'];
以上实例输出结果:
dict['Name']: Manni
#!/usr/bin/python dict = {['Name']: 'Zara', 'Age': 7}; print "dict['Name']: ", dict['Name'];以上实例输出结果:
Traceback (most recent call last): File "test.py", line 3, in <module> dict = {['Name']: 'Zara', 'Age': 7}; TypeError: list objects are unhashable
Python字典包含了以下内置函数:
序号 | 函数及描述 |
---|---|
1 | cmp(dict1, dict2) 比较两个字典元素。 |
2 | len(dict) 计算字典元素个数,即键的总数。 |
3 | str(dict) 输出字典可打印的字符串表示。 |
4 | type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。 |
详细解释:
1、描述
Python 字典(Dictionary) cmp() 函数比较两个字典元素。
2、语法
cmp()方法语法:
cmp(dict1, dict2)
3、参数
dict1 -- 比较的字典。
dict2 -- 比较的字典。
4、返回值
如果两个字典的元素相同返回0,如果字典dict1大于字典dict2返回1,如果字典dict1小于于字典dict2返回1。
5、实例
以下实例展示了 cmp()函数的使用方法:
#!/usr/bin/python dict1 = {'Name': 'Zara', 'Age': 7}; dict2 = {'Name': 'Mahnaz', 'Age': 27}; dict3 = {'Name': 'Abid', 'Age': 27}; dict4 = {'Name': 'Zara', 'Age': 7}; print "Return Value : %d" % cmp (dict1, dict2) print "Return Value : %d" % cmp (dict2, dict3) print "Return Value : %d" % cmp (dict1, dict4)
以上实例输出结果为:
Return Value : -1 Return Value : 1 Return Value : 0
1、描述
Python 字典(Dictionary) len() 函数计算字典元素个数,即键的总数。
2、语法
len()方法语法:
len(dict)
3、参数
dict -- 要计算元素个数的字典。
4、返回值
返回字典的元素个数。
5、实例
以下实例展示了 len()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7}; print "Length : %d" % len (dict)以上实例输出结果为:
Length : 2
1、描述
Python 字典(Dictionary) str() 函数将值转化为适于人阅读的形式,以可打印的字符串表示。
2、语法
str()方法语法:
str(dict)
3、参数
dict -- 字典。4、返回值
返回字符串。
5、实例
以下实例展示了 str()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7}; print "Equivalent String : %s" % str (dict)以上实例输出结果为:
Equivalent String : {'Age': 7, 'Name': 'Zara'}
1、描述
Python 字典(Dictionary) type() 函数返回输入的变量类型,如果变量是字典就返回字典类型。
2、语法
type()方法语法:
type(dict)
3、参数
dict -- 字典。
4、返回值
返回输入的变量类型。
5、实例
以下实例展示了 type()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7}; print "Variable Type : %s" % type (dict)
以上实例输出结果为:
Variable Type : <type 'dict'>
Python字典包含了以下内置函数:
序号 | 函数及描述 |
---|---|
1 | radiansdict.clear() 删除字典内所有元素 |
2 | radiansdict.copy() 返回一个字典的浅复制 |
3 | radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 |
4 | radiansdict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值 |
5 | radiansdict.has_key(key) 如果键在字典dict里返回true,否则返回false |
6 | radiansdict.items() 以列表返回可遍历的(键, 值) 元组数组 |
7 | radiansdict.keys() 以列表返回一个字典所有的键 |
8 | radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default |
9 | radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里 |
10 | radiansdict.values() 以列表返回字典中的所有值 |
详细解释:
1、描述
Python 字典(Dictionary) clear() 函数用于删除字典内所有元素。
2、语法
clear()方法语法:
dict.clear()
3、参数
NA。
4、返回值
该函数没有任何返回值。
5、实例
以下实例展示了 clear()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7}; print "Start Len : %d" % len(dict) dict.clear() print "End Len : %d" % len(dict)
以上实例输出结果为:
Start Len : 2 End Len : 0
1、描述
Python 字典(Dictionary) copy() 函数返回一个字典的浅复制。
2、语法
copy()方法语法:
dict.copy()
3、参数
NA。
4、返回值
返回一个字典的浅复制。
5、实例
以下实例展示了 copy()函数的使用方法:
#!/usr/bin/python dict1 = {'Name': 'Zara', 'Age': 7}; dict2 = dict1.copy() print "New Dictinary : %s" % str(dict2)
以上实例输出结果为:
New Dictinary : {'Age': 7, 'Name': 'Zara'}
1、描述
Python 字典(Dictionary) fromkeys() 函数用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。
2、语法
fromkeys()方法语法:
dict.fromkeys(seq[, value]))
3、参数
seq -- 字典键值列表。
value -- 可选参数, 设置键序列(seq)的值。
4、返回值
该方法返回列表。
5、实例
以下实例展示了 fromkeys()函数的使用方法:
#!/usr/bin/python seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq) print "New Dictionary : %s" % str(dict) dict = dict.fromkeys(seq, 10) print "New Dictionary : %s" % str(dict)
以上实例输出结果为:
New Dictionary : {'age': None, 'name': None, 'sex': None} New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
1、描述
Python 字典(Dictionary) get() 函数返回指定键的值,如果值不在字典中返回默认值。
2、语法
get()方法语法:
dict.get(key, default=None)
3、参数
key -- 字典中要查找的键。
default -- 如果指定键的值不存在时,返回该默认值值。
4、返回值
返回指定键的值,如果值不在字典中返回默认值None。
5、实例
以下实例展示了 get()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 27} print "Value : %s" % dict.get('Age') print "Value : %s" % dict.get('Sex', "Never")
以上实例输出结果为:
Value : 27 Value : Never
1、描述
Python 字典(Dictionary) has_key() 函数用于判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false。
2、语法
has_key()方法语法:
dict.has_key(key)
3、参数
key -- 要在字典中查找的键。
4、返回值
如果键在字典里返回true,否则返回false。
5、实例
以下实例展示了 has_key()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.has_key('Age') print "Value : %s" % dict.has_key('Sex')以上实例输出结果为:
Value : True Value : False
1、描述
Python 字典(Dictionary) items() 函数以列表返回可遍历的(键, 值) 元组数组。
2、语法
items()方法语法:
dict.items()
3、参数
NA。
4、返回值
返回可遍历的(键, 值) 元组数组。
5、实例
以下实例展示了 items()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.items()
以上实例输出结果为:
Value : [('Age', 7), ('Name', 'Zara')]
1、描述
Python 字典(Dictionary) keys() 函数以列表返回一个字典所有的键。
2、语法
keys()方法语法:
dict.keys()3、参数
NA。
4、返回值
返回一个字典所有的键。
5、实例
以下实例展示了 keys()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.keys()以上实例输出结果为:
Value : ['Age', 'Name']
1、描述
Python 字典(Dictionary) setdefault() 函数和get()方法类似, 如果键不已经存在于字典中,将会添加键并将值设为默认值。
2、语法
setdefault()方法语法:
dict.setdefault(key, default=None)3、参数
key -- 查找的键值。
default -- 键不存在时,设置的默认键值。
4、返回值
该方法没有任何返回值。
5、实例
以下实例展示了 setdefault()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.setdefault('Age', None) print "Value : %s" % dict.setdefault('Sex', None)以上实例输出结果为:
Value : 7 Value : None
1、描述
Python 字典(Dictionary) update() 函数把字典dict2的键/值对更新到dict里。
2、语法
update()方法语法:
dict.update(dict2)3、参数
dict2 -- 添加到指定字典dict里的字典。
4、返回值
该方法没有任何返回值。
5、实例
以下实例展示了 update()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7} dict2 = {'Sex': 'female' } dict.update(dict2) print "Value : %s" % dict以上实例输出结果为:
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
1、描述
Python 字典(Dictionary) values() 函数以列表返回字典中的所有值。
2、语法
values()方法语法:
dict.values()
3、参数
NA。
4、返回值
返回字典中的所有值。
5、实例
以下实例展示了 values()函数的使用方法:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7} print "Value : %s" % dict.values()以上实例输出结果为:
Value : [7, 'Zara']