B站|公众号:啥都会一点的研究生
hello,我是啥都生,本期将Python中字典涉及的从基础到进阶用法,全部总结归纳,一起看看吧
计算机中的标准数据结构通常称为“映射”。在Python中,这种结构称为“字典”。当有键/值对数据(一个映射到输出的输入)时,使用字典是最方便的
假设有如下数据
name = "CaiXK"
age = 38
height = 163.1415926
hobby = ["rap", "basketball", "python"]
location = (34.228, 26.093)
以name = "CaiXK"
为例,构成完整键值对,name
为键,"CaiXK"
为值。有两种构建列表的方式将上述数据进行存储,第一种,直接使用大括号,键与值间用冒号配对,键值对间用逗号隔开
dict1 = {"name" : "CaiXK", "age" : 38, "height" : 163.1415926, "hobby" : ["rap", "basketball", "python"], "location" : (34.228, 26.093)}
print(dict1)
>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093)}
第二种,使用内置方法dict()
,注意与第一种方法的区别,键值用等号连接,键值对依然用逗号隔开
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
print(dict1)
>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093)}
此外,使用fromkeys()
函数用于创建新字典,以序列中的元素做字典的键,所有键对应的初始值默认为None,可自定义初始值
keys = ('name', 'age', 'sex')
dict1 = dict.fromkeys(keys)
dict2 = dict.fromkeys(keys, 1)
print(dict1)
print(dict2)
>>> {'name': None, 'age': None, 'sex': None}
>>> {'name': 1, 'age': 1, 'sex': 1}
需特别注意的是,键不允许重复,若使用dict
方式创建字典并多次给同一个键赋值,则会触发报错
dict1 = dict(name = "ZhangS", name = "LiS", name = "CaiXK")
print(dict1["name"])
>>> File "script.py", line 5
dict1 = dict(name = "ZhangS", name = "LiS", name = "CaiXK")
^
SyntaxError: keyword argument repeated
Exited with error status 1
而使用大括号
方式创建,则只保留最后一次写入的键值对数据
dict1 = {"name" : "ZhangS", "name" : "LiS", "name" : "CaiXK"}
print(dict1["name"])
>>> CaiXK
此外,必须保证键是不可变,也就是仅支持数字、字符串、元组
dict1 = {1 : 2, (22, 33) : "44", "55" : 66}
print(dict1)
>>> {1: 2, (22, 33): '44', '55': 66}
字典创建完成后,可以看做N个输入对应N个输出,输入为键,输出为值,且不限定输出类型。字典的取值通过键完成索引,如下所示,注意使用中括号且引号别落下
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
name = dict1["name"]
hobby_1 = dict1["hobby"][0]
print(name, " is good at ", hobby_1)
>>> CaiXK is good at rap
如果试图访问取出不存在的键,则会抛出如下错误
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
Girlfriend = dict1["girlfriend"]
print(Girlfriend)
>>> Traceback (most recent call last):
File "script.py", line 3, in <module>
Girlfriend = dict1["girlfriend"]
KeyError: 'girlfriend'
Exited with error status 1
而使用get
获取键值,若键不存在,默认返回None,也支持自定义返回数据避免错误
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
Girlfriend = dict1.get("girlfriend")
print(Girlfriend)
Girlfriend = dict1.get("girlfriend", "Peter")
print(Girlfriend)
>>> None
>>> Peter
和get()
类似,若键不存在于字典中,使用setdefault
自定义值,默认为None,但不同的是,会将该键值对添加至字典中
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
Girlfriend = dict1.setdefault("girlfriend", "Peter")
print(Girlfriend)
print(dict1)
>>> Peter
>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093), 'girlfriend': 'Peter'}
因为字典是可变对象,支持修改,可以通过如下方式完成键值对的添加
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
dict1["girlfriend"] = "ZhangH" # Han
print(dict1)
>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093), 'girlfriend': 'ZhangH'}
通过索引键并重新赋值完成修改
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
dict1["girlfriend"] = "LiYF" # ?
print(dict1)
>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093), 'girlfriend': 'LiYF'}
使用del
删除指定键值对
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
del dict1["location"]
print(dict1)
>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python']}
也可以删除整个字典
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
del dict1
print(dict1)
>>> Traceback (most recent call last):
File "script.py", line 11, in <module>
print(dict1)
NameError: name 'dict1' is not defined
Exited with error status 1
使用pop
删除指定键值对并返回值
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
location = dict1.pop("location")
print(location, dict1)
>>> (34.228, 26.093) {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python']}
使用popitem
随机返回并删除字典中的最后一对键和值
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
data = dict1.popitem()
print(data, dict1)
>>> ('location', (34.228, 26.093)) {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python']}
使用clear
清空字典中的全部内容,注意与del
不同,该对象仍存在
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
dict1.clear()
print(dict1)
>>> {}
使用copy
完成字典的浅拷贝,避免因其可变带来的原始数据改动
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
dict2 = dict1
dict3 = dict1.copy()
dict1.popitem()
print(dict2)
print(dict3)
>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python']}
>>> {'name': 'CaiXK', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093)}
判断键是否存在于字典中使用in
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
if name in dict1:
print(True)
>>> True
使用update
将另一个字典中的键值对更新到本字典中,若键重复,则以另一字典为默认
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
dict2 = dict(name = "WuYF", sex = "Female")
dict1.update(dict2)
print(dict1)
>>> {'name': 'WuYF', 'age': 38, 'height': 163.1415926, 'hobby': ['rap', 'basketball', 'python'], 'location': (34.228, 26.093), 'sex': 'Female'}
然后说说列表的遍历,第一种,使用items
遍历每一个键值对
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
for item in dict1.items():
print(item)
>>> ('name', 'CaiXK')
('age', 38)
('height', 163.1415926)
('hobby', ['rap', 'basketball', 'python'])
('location', (34.228, 26.093))
第二种,使用keys
遍历字典中每个键,或者默认不使用内置方法
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
for key in dict1.keys(): # for key in dict1()
print(key)
>>> name
age
height
hobby
location
第三种,使用values
遍历字典中每个值
dict1 = dict(name = "CaiXK", age = 38, height = 163.1415926, hobby = ["rap", "basketball", "python"], location = (34.228, 26.093))
for value in dict1.values():
print(value)
>>> CaiXK
38
163.1415926
['rap', 'basketball', 'python']
(34.228, 26.093)
以上就是本期的全部内容,欢迎纠错与补充,整理不易,点赞收藏关注鼓励下吧,一起进步~