字典:{键:值,key: value}
# ==================== 创建字典 # 使用{}创建字典 scores = {'NANA':100, 'Layla':98, 'Vivian':45} print(scores) # {'NANA': 100, 'Layla': 98, 'Vivian': 45} # 内置函数 dict() student = dict(name='NANA', age=27) print(student) # {'name': 'NANA', 'age': 27} d = {} # 空字典 print(d) # {} # ==================== 获取元素 scores = {'NANA':100, 'Layla':98, 'Vivian':45} # 使用[] print(scores['NANA']) # 100 # 使用 .get() print(scores.get('NANA')) # 100 # 区别:当键不存在时: # print(scores['Zhenyi']) # error: KeyError print(scores.get('LP')) # None print(scores.get('LP',666)) # 666 指定默认值 get(查找键,默认输出) # ==================== 判断键存在否 scores = {'NANA':100, 'Layla':98, 'Vivian':45} print('NANA' in scores) # True print('NANA' not in scores) # False # 增 scores['Lynn'] = 88 print(scores) # {'NANA': 100, 'Layla': 98, 'Vivian': 45, 'Lynn': 88} # 改 scores['Lynn'] = 66 print(scores) # {'NANA': 100, 'Layla': 98, 'Vivian': 45, 'Lynn': 66} # 删 del scores['Vivian'] # 删除键值对 print(scores) # {'NANA': 100, 'Layla': 98, 'Lynn': 66} scores.clear() # 清空字典 print(scores) # {} # ==================== 获取字典视图 # 获取所有键 scores = {'NANA':100, 'Layla':98, 'Vivian':45} key = scores.keys() print(key) # dict_keys(['NANA', 'Layla', 'Vivian']) print(type(key)) # <class 'dict_keys'> print(list(key)) # ['NANA', 'Layla', 'Vivian'] 转list类型 # 获取所有值 value = scores.values() print(value) # dict_values([100, 98, 45]) print(type(value)) # <class 'dict_values'> print(list(value)) # [100, 98, 45] # 获取所有键值对 item = scores.items() print(item) # dict_values([100, 98, 45]) print(type(item)) # <class 'dict_items'> print(list(item)) # [('NANA', 100), ('Layla', 98), ('Vivian', 45)] 元组构成的列表 # ==================== 字典的遍历 scores = {'NANA':100, 'Layla':98, 'Vivian':45} for key in scores: # for 变量(键) in 字典 print(key, scores[key], scores.get(key)) '''NANA 100 100 Layla 98 98 Vivian 45 45''' # ==================== 字典的 tips # 1, 键不能重复,值可以重复 student = {'Name':'NANA', 'Name':'Layla'} print(student) # {'Name': 'Layla'} # 2, 字典元素无序(本质:哈希表) # 3, 字典的键是不可变对象(所以列表不可以作为键) # 4, 字典可以根据需要动态伸缩 # 5, 字典浪费内存,空间换时间(查询快但空间浪费) # ==================== 字典生成式 {键:值 for 键,值 in zip(键,值)} '''目标: name =['NANA', 'Layla', 'Vivian'] number = [100,98,45] ==> {'Name':'NANA', 'Name':'Layla'} ''' # 内置函数 zip() name =['NANA', 'Layla', 'Vivian'] number = [100,98,45,666,999] item = zip(name,number) # 可迭代对象 print(item) # <zip object at 0x0000022C1E6F93C8> d = {A.upper():B for A,B in item} # .upper() 表示大写 print(d) # {'NANA': 100, 'LAYLA': 98, 'VIVIAN': 45} # 即使key与value长度不匹配,以短的那个生成字典