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: {}
阅读全文
0 0
- Python全栈之路:字典dict常用方法
- python学习之路五--字典(dict)
- python---字典dict的常用方法和操作
- Python序列之字典(dict)
- Python基础之字典dict
- python dict常用方法简介
- python 字典Dict内建方法
- python 字典(dict)get方法应用
- python字典(dict)的get方法
- python字典(dict)get方法
- Python 中dict 字典方法小结
- Python 中dict字典get方法讲解
- Python全栈之路:string字符串常用方法
- Python全栈之路:list列表常用方法
- Python全栈之路:集合set常用方法
- Python中dict 字典
- python dict字典
- python dict字典
- phpstrom快捷键
- LeetCode 448 Find All Numbers Disappeared in an Array
- 在windows7下给vs2015配置dirent.h头文件
- 15.dubbo延迟连接、粘滞连接、令牌验证
- 《MySQL开发技巧》笔记
- Python全栈之路:字典dict常用方法
- Windows下JDK的安装配置
- 二叉树的前序遍历、中序遍历和后序遍历及其算法
- win7系统python安装
- java.io.IOException: Cannot run program "/opt/java/sdk/build-tools/23.0.1/aapt": error=2, No such fi
- Git 最基本的操作命令
- 习题8.2
- Android fragment与Activity交互
- @GeneratorValue与@GenericGenerator注解使用心得