一、什么是字典?
字典是另外一种可变容器类型,并且可以存储任意类型对象。列表元素进行修改的话,通过索引进行修改,如果当前元素的顺序发生改变,此时还需要修改索引才能成功完成元素的修改。
字典是Pytho 中唯一的映射类型。
- 字典创建语法:字典的创建使用{},每个键值对用冒号(:)分割,每对之间用逗号分隔。
- 字典的键必须独一无二,而值可以取任何数据类型,但必须是不可变的。
字典名={key1:value1,key2:value2}
- 示例
student = {'name': 'HunterArley', 'age': 24}
# 空字典
empty = {}
dict1 = dict(F=70, i=105, s=115, h=104, C=67)
print(dict1)
二、操作字典
2.1、访问字典
字典中根据键访问值,可以指定字典名和放在方括号内的键。
student = {'name': 'HunterArley', 'age': 24}
print(student['name'])
2.2、修改字典元素
字典元素是可以修改的,通过key找到具体元素之后,给一个新的元素值即可。
student = {'name': 'HunterArley', 'age': 24}
student['age'] = 25
print(student)
2.3、添加元素
动态的向字典中添加元素的时候,只要添加的键在字典中不存在,就会新增这个元素。
student = {'name': 'HunterArley', 'age': 24}
student['sex'] = '男'
print(student)
2.4、删除元素
- 使用del语句删除元素:del既可以删除指定的字典元素,也可以删除整个字典,如果不指定key,代表删除整个字典。
del 字典名[key]
- 使用clear()方法清空整个字典:被清空的字典最后会剩下一个空的字典,而用del删除的字典在程序当中就不存在了。
字典名.clear()
三、字典函数
函数 | 描述 | 示例 |
---|---|---|
len(dict) | 计算字典中的元素的个数 | student = {'name': 'HunterArley', 'age': 24} print(len(student)) |
str(dict) | 输出字典,用可打印的字符串表示 | student = {'name': 'HunterArley', 'age': 24} print(str(student)) |
type(variable) | 返回输入变量的数据类型 | student = {'name': 'HunterArley', 'age': 24} print(type(student)) |
dict.fromkeys(seq[,value]) | 创建一个新字典,以序列seq中元素做字典的值,value为字典所有键对应的初始值 | seq=('name','age','sex') dict1=dict.fromkeys(seq)print("新字典为:",dict1) dict2=dict.fromkeys(seq,'jack’) print("新字典为:",dict2) 输出结果:新字典为: {'name': None, 'age': None, 'sex': None}新字典为: {'name': 'jack', 'age': 'jack', 'sex': 'jack'} |
dict.get(key,default=None) | 返回指定键的值,如果值不在字典中返回default值 | dict1={'name':'tom','age':18} print ("age键的值为 : " ,dict1.get('age', 9)) print ("sex键的值为 : " ,dict1.get('sex', '男')) 输出结果:age键的值为 : 18 sex键的值为 : 男 |
key in dict | 如果键在字典dict里返回true,否则返回false | dict1={'name':['tom','jack'],'age':18,'sex':'男',18:19} if 'name' in dict1: print("键name在字典中存在") else: print("键name在字典中不存在") 输出结果: 键name在字典中存在 |
dict.keys() | 以列表返回一个字典所有的键 | dict1={'name':['tom','jack'],'age':18,'sex':'男',18:19} print(dict1.keys()) 输出结果: dict_keys(['name', 'age', 'sex', 18]) |
dict.setdefault(key,default=None) | 和get类似,但如果键不存在于字典中,将会添加键并将值设为default | dict1={'name':'tom','age':18} print ("age键的值为 : " ,dict1.setdefault('age', 9)) print ("sex键的值为 : " ,dict1.setdefault('sex', '男’)) print ("新字典为:",dict1) 输出结果: age键的值为 : 18 sex键的值为 : 男 新字典为: {'name': 'tom', 'age': 18, 'sex': '男’} |
dict.values() | 以列表返回一个字典中的所有值 | dict1={'name':'tom','age':18} print(dict1.values()) 输出结果: dict_values(['tom', 18]) |
'''
fromkeys()方法用于创建并返回一个新的字典,它有两个参数:
第一个参数是字典的键,第二个参数是可选的,是传入健对应的值。
'''
dict1 = {}
print(dict1.fromkeys((1, 2, 3)))
# {1: None, 2: None, 3: None}
dict2 = {}
print(dict2.fromkeys((1, 2, 3), 'Number'))
# {1: 'Number', 2: 'Number', 3: 'Number'}
dict3 = {}
print(dict3.fromkeys((1, 2, 3), ('one', 'two', 'three')))
# {1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
'''
keys()用于返回字典中的键
values()用于返回字典中所有的值
items()用于返回字典中所有的键值对
'''
dict1 = {}
dict1 = dict1.fromkeys(range(10), '赞')
print(dict1.keys())
# dict_keys([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(dict1.values())
# dict_values(['赞', '赞', '赞', '赞', '赞', '赞', '赞', '赞', '赞', '赞'])
print(dict1.items())
#dict_items([(0, '赞'), (1, '赞'), (2, '赞'), (3, '赞'), (4, '赞'), (5, '赞'), (6, '赞'), (7, '赞'), (8, '赞'), (9, '赞')])
'''
get()方法提供了更宽松的方式去访问字典项
'''
print(dict1.get(9))
# 赞
print(dict1.get(100))
# None
print(dict1.get(100, '木有'))
# 木有
# 如果不知道一个键是否在字典中,可以使用成员资格操作符来判断(in 或者 not in)
print(9 in dict1)
# True
print(100 in dict1)
# False
# 如果需要清空一个字典,则使用clear()方法
dict1.clear()
print(dict1)
# {}
'''
copy()方法是复制字典(浅拷贝)
'''
a = {1: 'one', 2: 'two', 3: 'three'}
b = a.copy()
print(id(a))
# 4332198360
print(id(b))
# 4366785056
a[1] = 'four'
print(a)
# {1: 'four', 2: 'two', 3: 'three'}
print(b)
# {1: 'one', 2: 'two', 3: 'three'}
'''
pop()是给定键弹出对应的值;
popitem()是弹出一个项;
'''
a = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
print(a.pop(2))
# two
print(a)
# {1: 'one', 3: 'three', 4: 'four'}
print(a.popitem())
# (4, 'four')
print(a)
# {1: 'one', 3: 'three'}
'''
setdefault()在字典中找不到相应的键时会自动添加;
'''
a = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}
print(a.setdefault(3))
# three
print(a.setdefault(5))
# None
print(a)
# {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: None}
四、浅拷贝与深拷贝
Python中string、tuple和number是不可变对象,而dict、list等是可变对象;不可变对象在进行重新赋值的时候,实际上是将原始值丢弃,将变量指向一个新值;可变对象的可变性实质上是指更改可变对象中的子对象,比如list中的item元素的更改。
- 直接赋值:其实就是对象的引用(别名)。
- 浅拷贝:不拷贝子对象(针对子对象中的item),当子对象进行更改的时候,原始对象也会改变。
- 列表的切片操作
- list()操作
- copy()函数
- copy模块的copy()函数
- 深拷贝:会拷贝子对象,当原始对象的子对象进行更改的时候,原始对象不会改变。
- copy模块的deepcopy()函数
学海无涯苦作舟

网友评论