python之字典相关功能举例
# 字典相关功能举例 person = {'name': 'Mike', 'age': 25} print("初始的数据字典:", person) # {'name': 'Mike', 'age': 25} person2 = dict(name="Mike", age=25) print("初始的数据字典2:", person2) # {'name': 'Mike', 'age': 25} # 访问字典值 print("获取姓名:", person['name']) # Mike print("获取姓名2:", person.get("name", "没有找到name")) # Mike 没有找到返回默认值 # 遍历字典 print("遍历字典:") for key, value in person.items(): print(key, value) """ name Mike age 25 """ # 遍历字典获取指定值 print("字典中获取指定值", {k: v for k, v in person.items() if k == "name"}) # {'name': 'Mike'} print("字典中获取指定值2", {k: v for k, v in person.items() if k == "name"}.get("name", None)) # Mike print("字典中获取指定值3", [v for k, v in person.items() if k == "name"]) # ['Mike'] print("字典中获取指定值4", [v for k, v in person.items() if k == "不存在"]) # [] # 添加键值对 person['job'] = 'singer' print("添加后的数据字典:", person) # {'name': 'Mike', 'age': 25, 'job': 'singer'} print(person.setdefault("job", "teacher")) # singer key不存在才会插入,返回当前值 # 修改值 person['age'] = 30 print("修改后的数据字典:", person) # {'name': 'Mike', 'age': 30, 'job': 'singer'} person.update({'name': 'Jim', 'age': 12}) person.update(name='Jim2', age=13) print("修改后的数据字典2:", person) # {'name': 'Jim2', 'age': 13, 'job': 'singer'} # 删除键值对 del person['job'] print("删除后的数据字典:", person) # {'name': 'Jim2', 'age': 13} # 清空字典 person.clear() # 快速初始化字典 myDict = dict.fromkeys("abc", 123) print(myDict) # {'a': 123, 'b': 123, 'c': 123} print(myDict.pop("a")) # 123 弹出"a"的值,并删除原字典的值 print(myDict.popitem()) # ('c', 123) 弹出字典最后一个键值对,并在原字典中删除 print(myDict) # {'b': 123} 字典中的剩余的值 # 视图,原数据修改则跟着修改 myDict.keys() # key的视图 myDict.values() # 值的视图 myDict.items() # 键值对的视图 # 字典转换为列表 myDict = dict.fromkeys("abc", 123) print(list(myDict)) # ['a', 'b', 'c'] print(list(myDict.values())) # [123, 123, 123] # 字典推导式 d = {x: ord(x) for x in "abcde"} print(d) # {'a': 97, 'b': 98, 'c': 99, 'd': 100, 'e': 101} dd = {v: k for k, v in d.items() if v > 99} print(dd) # {100: 'd', 101: 'e'} # 字典中嵌套列表及其遍历 hobbys = {'Mike': ['singing', 'swim', 'reading'], 'Tom': ['reading', 'dance']} for key, values in hobbys.items(): print(key + "的爱好是:") for h in values: print(h) """ Mike的爱好是: singing swim reading Tom的爱好是: reading dance """