于2017-07-06由小牛君创建
键在一个字典中是唯一的,而值则可以重复。字典的值可以是任何类型,但键必须是不可变的数据的类型,例如:字符串,数字或元组这样的类型。
要访问字典元素,你可以使用方括号和对应键,以获得其对应的值。下面是一个简单的例子 -
#!/usr/bin/python3 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/python3 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/python3 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
可以删除单个字典元素或清除字典的全部内容。也可以在一个单一的操作删除整个词典。
#!/usr/bin/python3 dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name'] # remove entry with key 'Name' dict.clear() # remove all entries in dict del dict # delete entire dictionary print ("dict['Age']: ", dict['Age']) print ("dict['School']: ", dict['School'])
dict['Age']: Traceback (most recent call last): File "test.py", line 8, in <module> print "dict['Age']: ", dict['Age']; TypeError: 'type' object is unsubscriptable
字典的值没有限制。它们可以是任意Python对象,无论是标准的对象或用户定义的对象。但是,键却不能这样使用。
(一)每个键对应多个条目是不允许的。这意味着重复键是不允许的。当键分配过程中遇到重复,以最后分配的为准。例如 -
#!/usr/bin/python3 dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'} print ("dict['Name']: ", dict['Name'])
dict['Name']: Manni
(二)键必须是不可变的。这意味着可以使用字符串,数字或元组作为字典的键,但是像['key']是不允许的。下面是一个简单的例子:
#!/usr/bin/python3 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
SN |
函数与描述
|
---|---|
1 |
比较这两个字典的元素。
|
2 |
计算字典的总长度。这等于字典中的项的数目。
|
3 |
产生字典的可打印字符串表示
|
4 |
返回传递变量的类型。如果传递变量是字典,那么它会返回一个字典类型。 |
SN |
描述与方法
|
---|---|
1 |
删除字典 dict 中的所有元素
|
2 |
返回字典 dict 的浅表副本
|
3 |
使用seq的键和值来设置创建新字典
|
4 |
对于键key,返回其值或default如果键不存在于字典中
|
5 |
返回true如果在字典dict有存在键key,否则为false
|
6 |
返回 dict (键,值)元组对的列表
|
7 |
返回字典 dict 的键列表
|
8 |
dict.setdefault(key, default=None)
类似于get()方法,但会设定dict[key]=default,如果键不存在于dict中
|
9 |
添加字典dict2的键值对到dict
|
10 |
返回字典dict值列表
|
在线咨询
免费热线
资料发放
技术答疑
关注微信