Python全栈之路:字典dict常用方法

来源:互联网 发布:js实现下拉菜单 编辑:程序博客网 时间:2024/06/05 10:53

    • 特性
    • 创建字典
      • way 1小心列表坑
      • way 2
    • 字典无序输出
    • 查询
    • 修改
    • 增加
    • 删除
    • 遍历
    • 清空

特性:

  • dict无序
  • key唯一,天生去重

创建字典

way 1:(小心列表坑!)

d = dict.fromkeys([1, 2, 3], ["name", "age"])print("d:", d)# ->d: {1: ['name', 'age'], 2: ['name', 'age'], 3: ['name', 'age']}d[1][0] = "company"  # 浅拷贝print("d of modify:", d)  # 此处,列表中的信息都被修改了# ->d of modify: {1: ['company', 'age'], 2: ['company', 'age'], 3: ['company', 'age']}

way 2:

info = {    "teacher1": "苍井空",    "teacher2": "小泽玛利亚",    "teacher3": "泷泽萝拉"}

字典无序输出

print("info", info)# ->info {'teacher2': '小泽玛利亚', 'teacher3': '泷泽萝拉', 'teacher1': '苍井空'}

查询

print(info["teacher1"])  # 不存在则报错# ->苍井空print(info.get("teacher5"))  # 推荐方式,不会报错# ->Noneprint("teacher1" in info)  # py2:info.has_key("teacher5")# ->Trueprint("keys:", info.keys())# ->keys: dict_keys(['teacher2', 'teacher1', 'teacher3'])print("values:", info.values())# ->values: dict_values(['小泽玛利亚', '苍井空', '泷泽萝拉'])print("items:", info.items())# ->items: dict_items([('teacher2', '小泽玛利亚'),# ('teacher1', '苍井空'), ('teacher3', '泷泽萝拉')])

修改

info["teacher1"] = "天海翼"  # 存在会被修改print("modify:", info)# ->modify: {'teacher2': '小泽玛利亚', 'teacher1': '天海翼', 'teacher3': '泷泽萝拉'}

增加

info["teacher4"] = "上原瑞穗"  # 没有则会创建info.setdefault("teacher1", "樱井莉亚")  # 存在则不会被修改print("add:", info)# ->add: {'teacher4': '上原瑞穗', 'teacher2': '小泽玛利亚',# 'teacher3': '泷泽萝拉', 'teacher1': '天海翼'}b = {    "teacher1": "樱井莉亚",    "teacher5": "桃谷绘里香"}info.update(b)print("update:", info)# ->update: {'teacher1': '樱井莉亚', 'teacher4': '上原瑞穗',#  'teacher2': '小泽玛利亚', 'teacher3': '泷泽萝拉', 'teacher5': '桃谷绘里香'}

删除

del info["teacher1"]info.pop("teacher2")  # 标准写法info.popitem()  # 随机删除一个print("delete:", info)# ->delete: {'teacher5': '桃谷绘里香', 'teacher3': '泷泽萝拉'}

遍历

for i in info:  # 推荐print(i, info[i])# teacher5 桃谷绘里香# teacher3 泷泽萝拉print("*"*50)for key, value in info.items():  # 先转列表,在遍历,如果字典过大,会变慢print(key, value)# teacher5 桃谷绘里香# teacher3 泷泽萝拉

清空

info.clear()print("clear:", info)# ->clear: {}
原创粉丝点击