目录
1 字典
字典是一个用来存储键值对的数据结构,也就是Java中的Map(映射),底层实现可以有TreeMap和HashMap,而在python中就叫做字典。TreeMap使用红黑树实现(可见:映射TreeMap的实现),HashMap则使用哈希表实现(哈希表的实现思路并不难,但具体的实现细节非常复杂),而python中的字典肯定是用哈希表实现的,因为哈希表性能更高,存取数据的时间复杂度为O(1)。
1.1 字典的创建
- 符号为⼤括号
- 数据为键值对形式出现
- 各个键值对之间⽤逗号隔开
1.1.1创建有初始值的字典
#建立有数据的字典
dict1={1:"hello", 34:"world", 11:"monster"}
print(dict1)
{1: 'hello', 34: 'world', 11: 'monster'}
1.1.2创建空字典
#建立无数据的字典
#方法一
dict2={}
#方法二
dict3=dict()
print(dict3)
{}
1.2 增加修改字典
直接在下标写key,等号右边写value。
写法:字典序列[key] = 值
注意:如果key存在则修改这个key对应的值;如果key不存在则新增此键值对。
1.2.1 增加键值对
#增加元素
dict1={}
dict1[3.14]="pi"
dict1["hello"]="wolrd"
print(dict1)
{3.14: 'pi', 'hello': 'wolrd'}
1.2.2 修改键值对
#修改元素
dict1={3.14: 'pi', 'hello': 'wolrd'}
dict1[3.14]="天王盖地虎"
print(dict1)
{3.14: '天王盖地虎', 'hello': 'wolrd'}
1.3 删除键值对或者整个字典
del() / del:删除字典或删除字典中指定键值对。
1.3.1 删除键值对
#删除字典中元素
dict1={34:"hello",6:"Tom",55:"Maria"}
del(dict1[6])
print(dict1)
{34: 'hello', 55: 'Maria'}
1.3.2 删除整个字典
#删除整个字典
dict1={34:"hello",6:"Tom",55:"Maria"}
del(dict1)
print(dict1)
NameError: name 'dict1' is not defined
由于dict1字典不存在了,发生dict1未定义的报错。
1.3.3 清空字典
#清空字典
dict1={34:"hello",6:"Tom",55:"Maria"}
dict1.clear()
print(dict1)
{}
1.4 修改键值对
写法:字典序列[key] = 值
注意:如果key存在则修改这个key对应的值 ;如果key不存在则新增此键值对。
dict1={34:"hello",6:"Tom",55:"Maria"}
dict1[6]="Tony"
print(dict1)
{34: 'hello', 6: 'Tony', 55: 'Maria'}
1.5 获取字典中的元素
1.5.1 通过key获取value
方法一:在索引中写key
#通过key获取value
dict1={34:"hello",6:"Tom",55:"Maria"}
print(dict1[55])
Maria
方法二:通过get方法
字典序列.get(key, 默认值)
注意:如果当前查找的key不存在则返回第⼆个参数(默认值),如果省略第⼆个参数,则返回None。
dict1={34:"hello",6:"Tom",55:"Maria"}
# get方法,通过key获取value
print(dict1.get(6))
print(dict1.get(343,"没有该键值对"))
print(dict1.get(344))
Tom
没有该键值对
None
1.5.2 获取字典中所有的key
通过keys方法,获取所有的key,返回值为一个可迭代对象,可用于遍历。
dict1={34:"hello",6:"Tom",55:"Maria"}
keyList=dict1.keys()
print(keyList)
dict_keys([34, 6, 55])
1.5.2 获取字典中所有的value
通过values方法,获取所有的value,返回值为一个可迭代对象,可用于遍历。
dict1={34:"hello",6:"Tom",55:"Maria"}
valueList=dict1.values()
print(valueList)
dict_values(['hello', 'Tom', 'Maria'])
1.5.2 获取字典中所有的键值对
通过items方法,获取所有的键值对,每一个键值对用元组存储,返回值为一个可迭代对象,可用于遍历。
dict1={34:"hello",6:"Tom",55:"Maria"}
itemList=dict1.items()
print(itemList)
dict_items([(34, 'hello'), (6, 'Tom'), (55, 'Maria')])
1.6 字典的遍历
通过以上的方法获取想要遍历的数据序列,再使用for循环遍历即可。
1.6.1 key的遍历
dict1={34:"hello",6:"Tom",55:"Maria"}
for key in dict1.keys():
print(key,end=" ")
34 6 55
1.6.2 value的遍历
dict1={34:"hello",6:"Tom",55:"Maria"}
for value in dict1.values():
print(value,end=" ")
hello Tom Maria
1.6.3 键值对的遍历
#拆包
for key,value in dict1.items():
#print(f'键:{key}值:{value}',end=" ")
print("键:%d 值:%s" % (key,value),end=" ")
键:34 值:hello 键:6 值:Tom 键:55 值:Maria