一个无序以键值对方式存储数据的容器,key不能重复。字典用大括号{}表示。
1、字典的访问
字典与集合相似,都是用大括号表示。但,二者有个根本的不同,字典是键值对,每个元素不是单独的值。
1.1、通过键访问
字典无法用 字典名[index] 的方式访问,可通过访问键的方式访问到值。
若访问的键不存在,会报错。
示例:
dict1 = {"0":1,1:1}
print(dict1["0"])
print(dict1[1])
print(dict1[0])

1.2、get访问
除了键的方式访问,还可以用get函数。
get:提供字典的键,访问键对应的值。
参数:get[key,value]
key:输入的键。
value:当查询的键不存在,可通过设定默认值,让其返回这个默认值。(可选)
示例:
dict1 = {"0":1,1:1}
print(dict1.get("0",100))
print(dict1.get(0,99))

1.3、获取字典所有的key
keys:这个方法可获取字典所有的key。
返回值:字典类型的key。
示例:
dict1 = {"0":1,1:1}
print(dict1.keys(),type(dict1.keys()))

1.4、获取字典所有的value
values:这一方法可获取字典所有的value。
返回值:字典类型的value。
示例:
dict1 = {"0":1,1:1}
print(dict1.values(),type(dict1.values()))

1.5、获取字典所有的键值对
items:这一方法获取字典中所有key,value。
返回值:字典类型的key,value
示例:
dict1 = {"0":1,1:1}
print(dict1.items(),type(dict1.items()))

2、字典的添加
2.1、直接添加
字典可通过 字典名[key] 访问的方式直接添加。
示例:
dict1 = {"0":1,1:1}
dict1[2] = 2
print(dict1)

2.2、update添加
update:接收多个键值对,添加到字典中。
返回值:无。
示例:
dict1 = {"0":1,1:1}
dict2 = dict1.update({2:2,3:3})
print(dict1)
print(dict2)

3、字典的修改
其方法通字典的添加一样,都可以通过 字典名[key] 和update方式进行修改。
示例:
dict1 = {"0":1,1:1}
dict1["0"] = 0
dict1.update({1:666})
print(dict1)

4、字典的删除
4.1、pop
pop:输入键,删除字典的键值对。
返回值:成功则返回被删除键对应的值,失败会报错。
示例:
dict1 = {"0":1,1:1}
value_dict1 = dict1.pop("0")
print(dict1)
print(value_dict1)
dict1.pop(666)

4.2、del
del:根据字典的键,删除字典键值对。失败会报错。
示例:
dict1 = {"0":1,1:1}
del dict1["0"]
print(dict1)
del dict1[666]
