Python字典详解:数据存储与管理

发表时间: 2024-04-01 12:14

字典组成

字典由键(key)和值(value)组成;字典元素由{}括在一起

dic = {key1 : value1, key2 : value2 }

key是字典中的键,value是该键对应的值;key : value称之为键值对

字典的创建

# 直接按照定义创建d = {"name":"zhangsan", "age":18, "sex":"man"}print(d)
{'name': 'zhangsan', 'age': 18, 'sex': 'man'}
  • dict()
# 使用dict()方法d = dict(name = "zhangsan", age = 18, sex = "man")print(d)
{'name': 'zhangsan', 'age': 18, 'sex': 'man'}
# 使用dict()方法 ,将一个元组列表转换为字典l = [("name" , "zhangsan"), ("age" , 18), ("sex" ,"man")]d = dict(l)print(d)
{'name': 'zhangsan', 'age': 18, 'sex': 'man'}
# 使用dict()方法 ,将一个打包后的元组转换为字典key = ("name", "age", "sex")value = ("zhangsan", 18, "man")d = dict(zip(key,value))print(d)
{'name': 'zhangsan', 'age': 18, 'sex': 'man'}
  • 使用推导式
dn = {a:a ** 2 for a in range(5)}print(dn)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
  • 使用zip()将两个序列绑定
l = ["name","age","sex"]l1 = ["lisi",18,"man"]d = dict(zip(l,l1))print(d)
{'name': 'lisi', 'age': 18, 'sex': 'man'}

字典访问

不同于列表元素只能用整数下标访问,字典的key值可以是整数、字符串、元组等,但是不可以用列表,因为列表的值可以是可以改变的。

print(d["name"])
zhangsan

字典的key值是唯一的,但是其对应的值是可修改的

# 通过key访问修改其对应的值valued["name"] = "lisi"print(d)
{'name': 'lisi', 'age': 18, 'sex': 'man'}
# 删除字典的键值对del d["age"]print(d)
{'name': 'zhangsan', 'sex': 'man'}
# 遍历字典for key in d:    print('**key:{}'.format(key))for value in d:    print('##value:{}'.format(value))for itme in d.items():    print('$$itme:{}'.format(itme))for key,value in d.items():    print('&&key:{},value:{}'.format(key,value))
**key:name**key:sex##value:name##value:sex$$itme:('name', 'zhangsan')$$itme:('sex', 'man')&&key:name,value:zhangsan&&key:sex,value:man

字典的方法

  • 字典的长度(键值对个数)
# len()print(len(d))
2
  • 将字典传换为字符串输出
# str()s = str(d)print(s)print(type(s))
{'name': 'zhangsan', 'sex': 'man'}<class 'str'>
  • 字典拷贝
# copy()d1 = d.copy()print(d1)d["name"] = "lisi" # d的修改不会影响到d1print(d)print(d1)
{'name': 'zhangsan', 'sex': 'man'}{'name': 'zhangsan', 'sex': 'man'}
  • 给指定的key值创建出字典
# fromkeys()keys = ['name','age','sex']# 不指定value,就是Noned = dict.fromkeys(keys)print(d)# 指定默认valued = dict.fromkeys(keys,"zhangsan")print(d)
{'name': None, 'age': None, 'sex': None}{'name': 'zhangsan', 'age': 'zhangsan', 'sex': 'zhangsan'}
  • 获取指定key对应的value
# get()d = dict(name = "zhangsan", age = 18, sex = "man")print(d.get("name"))# 没有对应的值时,返回Noneprint(d.get("addr"))# 可以返回指定的值print(d.get("addr","xian"))print(d)
zhangsanNonexian{'name': 'zhangsan', 'age': 18, 'sex': 'man'}
  • 设置默认键值
# setdefault()# 和get()类似,在key的值不存在时,可设置默认值,不同的是setdefault()会将设置的默认键值对添加到字典中d.setdefault("name","lisi")print(d)d.setdefault("addr","Xian")print(d)
{'name': 'zhangsan', 'age': 18}{'name': 'zhangsan', 'age': 18, 'addr': 'Xian'}
  • 获取字典中的键值对
# items()items = d.items()print(items)print(type(items))# 可通过list()将其转换为列表l = list(items)print(l)print(type(l))# 可用于遍历字典for item in d.items():    print(item)
dict_items([('name', 'zhangsan'), ('age', 'zhangsan'), ('sex', 'zhangsan')])<class 'dict_items'>[('name', 'zhangsan'), ('age', 'zhangsan'), ('sex', 'zhangsan')]<class 'list'>('name', 'zhangsan')('age', 'zhangsan')('sex', 'zhangsan')
  • 删除字典最后一个键值对
# popitem()print(d)print("del item is ",d.popitem())print(d)
{'name': 'zhangsan', 'age': 18, 'addr': 'Xian'}del item is  ('addr', 'Xian'){'name': 'zhangsan', 'age': 18}
  • 删除指定key对应的键值对
# pop()d = dict(name = "zhangsan", age = 18, sex = "man")print(d)# key值不存在会报 KeyErrorprint("del key is age value is ",d.pop("age"))print(d)
{'name': 'zhangsan', 'age': 18, 'sex': 'man'}del key is age value is  18{'name': 'zhangsan', 'sex': 'man'}
  • 更新字典
# update()# 键值对存在就更新,不存在则添加print(d)d.update({"name":"lisi"})print(d)d1 = {"name":"zhangsan", "addr":"xian"}d.update(d1)print(d)
{'name': 'zhangsan', 'sex': 'man', 'addr': 'xian'}{'name': 'lisi', 'sex': 'man', 'addr': 'xian'}{'name': 'zhangsan', 'sex': 'man', 'addr': 'xian'}