python基础学习(九)字典
字典的定义
lierge = {"name": "李二哥", "age": 18, "height": 1.66}
字典常用操作
- 在ipython3中定义一个字典,例如:dict = {}
- 输入dict. 按下Tab键,ipython3会提示字典能使用的方法如下:
- 字典的常用操作:
- 取值:dict[key]
# 1. 取值 print(zhangsan_dict["name"]) # 注意,在取值时,如果指定的key不存在,程序会报错
- 增加/修改:dict[key] = xxxx
# 2. 增加/修改 zhangsan_dict["name"] = "张三三" zhangsan_dict["weight"] = 66
- 删除:dict.pop(key)
# 3. 删除操作 zhangsan_dict.pop("name") # 注意,在删除时,如果指定的key不存在,程序会报错 # zhangsan_dict.pop("xxxx")
- 统计:len(dict)
# 4. 统计键值对数量 print(len(zhangsan_dict))
- 合并字典:dict.update(dict)
# 5. 合并字典 temp_dict = {"weight": 88} zhangsan_dict.update(temp_dict)
- 清空字典:dict.clear()
# 6. 清空字典 zhangsan_dict.clear()
- 取值:dict[key]
字典的遍历
zhangsan_dict = {"name": "张三", "age": 18, "height": 1.66} for key in zhangsan_dict: print("%s: %s" % (key, zhangsan_dict[key]))
字典的应用场景
person = [ {"name": "张三", "age": 18, "height": 1.66}, {"name": "李四", "age": 17, "height": 1.88} ] for p in person: print(p)
--本文完--
本文来自博客园,作者:coder-qi,转载请注明原文链接:https://www.cnblogs.com/coder-qi/p/python-dictionary.html