1.前言

字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,因此,字典的key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元组。

字典的键必须是唯一的,但值则不必。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

2.定义字典

字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中

  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. print(dic)
  3. #输出
  4. {'name': 'nanliangrexue', 'age': 18}

3.字典的增删改查

给原有的字典增加新的键值对

  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. dic['gender'] = 'male'
  3. print(dic)
  4. #输出
  5. {'name': 'nanliangrexue', 'age': 18, 'gender': 'male'}

  • del:删除字典中的某个键值对
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. del dic['age']
  3. print(dic)
  4. #输出
  5. {'name': 'nanliangrexue'}
  • pop():删除字典中的某个键值对,并返回被删除的键值对
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. print(dic.pop('age'))
  3. print(dic)
  4. #输出
  5. 18
  6. {'name': 'nanliangrexue'}
  • popitem():随机删除字典中的一对键和值并以元组形式返回被删除的键值对
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. print(dic.popitem())
  3. print(dic)
  4. #输出
  5. ('age', 18)
  6. {'name': 'nanliangrexue'}
  • 删除整个字典
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. del dic
  3. print(dic)
  4. #输出报错,因为字典已经被删除
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. NameError: name 'dic' is not defined
  • clear():清空字典
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. dic.clear()
  3. print(dic)
  4. #输出
  5. {}

要修改字典中已有键/值对,只需给要修改的键值对的键值重新赋值即可

  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. dic['age'] = 28
  3. print(dic)
  4. #输出
  5. {'name': 'nanliangrexue', 'age': 28}

  • 按键值key查找,如果查找不到会报错
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. print(dic['name'])
  3. print(dic['age'])
  4. print(dic['gender'])
  5. #输出
  6. 'nanliangrexue'
  7. 18
  8. Traceback (most recent call last):
  9. File "<stdin>", line 1, in <module>
  10. KeyError: 'gender'
  • get查找,如果查找不到会返回None,不会报错
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. print(dic.get('name'))
  3. print(dic.get('age'))
  4. print(dic.get('gender'))
  5. #输出
  6. 'nanliangrexue'
  7. 18
  8. None

4.字典的方法

  • dict.fromkeys(键,值)

    创建一个新字典,键必须是可迭代的数据类型(列表,元祖,字符串,集合,字典),值就是每个键值对中默认的值
  1. dict1 = dict.fromkeys([1,2,3],'china')
  2. dict2 = dict.fromkeys('name','china')
  3. print(dict1)
  4. print(dict2)
  5. #输出
  6. {1: 'china', 2: 'china', 3: 'china'}
  7. {'n': 'china', 'a': 'china', 'm': 'china', 'e': 'china'}
  • dict.get(key, default=None)

    返回指定键的值,如果值不在字典中返回default值
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. print(dic.get('name'))
  3. print(dic.get('gender'))
  4. print(dic.get('gender','您所查找的键值不存在!'))
  5. #输出
  6. 'nanliangrexue'
  7. None
  8. '您所查找的键值不存在!'
  • dict.items()

    以列表形式返回可遍历的(键, 值) 元组数组
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. print(dict1.items())
  3. #输出
  4. dict_items([(1, 'china'), (2, 'china'), (3, 'china')])
  • dict.keys()

    以列表形式返回字典中所有的键
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. print(dict1.keys())
  3. #输出
  4. dict_keys([1, 2, 3])
  • dict.setdefault(key, default=None)

    和get()类似,也是查找指定键的值, 但如果查找的键不存在于字典中,将会添加键并将值设为default
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. print(dic.setdefault('name'))
  3. print(dic.setdefault('gender','male'))
  4. print(dic)
  5. #输出
  6. 'nanliangrexue'
  7. 'male'
  8. {'name': 'nanliangrexue', 'age': 18, 'gender': 'male'}
  • dict.update(dict2)

    把字典dict2的键值对增加到dict1里,即就是把dict1和dict2合并成一个字典
  1. dic1 = { 'name' : 'nanliangrexue','age':18}
  2. dic2 = { 'gender' : 'male'}
  3. dic1.update(dic2)
  4. print(dic1)
  5. #输出
  6. {'name': 'nanliangrexue', 'age': 18, 'gender': 'male'}
  • dict.values()

    以列表形式返回字典中的所有值
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. print(dic.values())
  3. #输出
  4. dict_values(['nanliangrexue', 18])

5.字典的遍历

  • 遍历字典的key
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. for key in dic.keys():
  3. print(key)
  4. #输出
  5. 'name'
  6. 'age'
  • 遍历字典中的value
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. for value in dic.values():
  3. print(value)
  4. #输出
  5. 'nanliangrexue'
  6. 18
  • 同时遍历字典中的key和value,以元组形式返回
  1. dic = { 'name' : 'nanliangrexue','age':18}
  2. for item in dic.items():
  3. print(item)
  4. #输出
  5. ('name', 'nanliangrexue')
  6. ('age', 18)

python学习之【第六篇】:Python中的字典及其所具有的方法的更多相关文章

  1. Python学习笔记(六)Python组合数据类型

    在之前我们学会了数字类型,包括整数类型.浮点类型和复数类型,这些类型仅能表示一个数据,这种表示单一数据的类型称为基本数据类型.然而,实际计算中却存在大量同时处理多个数据的情况,这种需要将多个数据有效组 ...

  2. Python 学习 第十六篇:networkx

    networkx是Python的一个包,用于构建和操作复杂的图结构,提供分析图的算法.图是由顶点.边和可选的属性构成的数据结构,顶点表示数据,边是由两个顶点唯一确定的,表示两个顶点之间的关系.顶点和边 ...

  3. Python学习第十六篇——异常处理

    在实际中,很多时候时候,我们并不能保证我们所写的程序是完美的.比如我们程序的本意是:用户在输入框内输入数字,并进行后续数学运算,即使我们提醒了用户需要输入数字而不是文本,但是有时会无意或者恶意输入字符 ...

  4. python学习【第六篇】python迭代器与生成器

    一.什么是迭代器 迭代器协议:对象必须提供一个next方法,执行该方法要么返回迭代中的下一项,要么就引起一个StopIteration异常,以终止迭代(只能往后走不能往前退) 可迭代对象:实现了迭代器 ...

  5. Python学习【第六篇】运算符

    运算符 算数运算: a = 21 b = 10 c = 0 c = a + b print ("1 - c 的值为:", c) c = a - b print ("2 - ...

  6. [Python学习笔记][第六章Python面向对象程序设计]

    1月29日学习内容 Python面向对象程序设计 类的定义与使用 类定义语法 使用class关键词 class Car: def infor(self): print("This is ca ...

  7. Python 学习笔记(六)Python第一个程序

    Python 语句 赋值语句 1.将3对象赋值给了变量a 2.将3,4赋值给了变量a,b >>> a = 3 >>> a ,b = 3,4 >>> ...

  8. Python之路(第六篇)Python全局变量与局部变量、函数多层嵌套、函数递归

    一.局部变量与全局变量 1.在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量.全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序. 全局变量没有任何缩进,在任何位置都可 ...

  9. Python学习笔记之基础篇(五)字典

    #数据类型划分:可变数据类型 不可变数据类型 #不可变数据类型 : 元组 bool int str --> 可哈希 #可变数据类型 list ,dict set --->不可哈希 ''' ...

  10. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

随机推荐

  1. Android实现apk插件方式换肤

    换肤思路: 1.什么时候换肤? xml加载前换肤,如果xml加载后换肤,用户将会看见换肤之前的色彩,用户体验不好. 2.皮肤是什么? 皮肤就是apk,是一个资源包,包含了颜色.图片等. 3.什么样的控 ...

  2. 服务网关Spring Cloud Zuul

    Spring Cloud Zuul 开发环境 idea 2019.1.2 jdk1.8.0_201 Spring Boot 2.1.9.RELEASE Spring Cloud Greenwich S ...

  3. C# 8 的模式匹配

    C# 7 里面的Pattern Mathing is 模式 switch 和 when C# 8 里面的Pattern Matching 使用Deconstructor 和 位置匹配模式 下面两个类T ...

  4. CSS ellipsis 与 padding 结合时的问题

    CSS 实现的文本截断 考察如下代码实现文本超出自动截断的样式代码: .truncate-text-4 { overflow: hidden; text-overflow: ellipsis; dis ...

  5. Angry Words 愤怒的话

    _ Words said in anger are like scars left by nails in a fence. Even though you can pull all the nail ...

  6. Django高级实战 开发企业级问答网站 ✌✌

    Django高级实战 开发企业级问答网站 (一个人学习或许会很枯燥,但是寻找更多志同道合的朋友一起,学习将会变得更加有意义✌✌) 从实际需求分析开始,实现当今主流知识问答应用的功能,包括动态.文章.问 ...

  7. 异常:微信小程序tabBar不生效

    app.json全局tabBar设置tabBar不显示 由于小程序的机制问题,首页的tabBar第一个导航必须是首页 "pages": [ "pages/index/in ...

  8. 配置Ant执行Jmeter脚本

    1.将 jmeter下extras目录中ant-jmeter-1.1.1.jar包拷贝至ant安装目录下的lib目录中,否则会报错ant-jmeter-1.1.1不存在 2.在jmeter根目录下创建 ...

  9. 简单了解工作空间工厂(IWorkspaceFactory)

    工作空间工厂(WorkspaceFactory)是工作空间的发布者,允许客户连接通过一组连接属性定义的工作空间. 工作空间表达了一个包含一个或多个数据集的数据库或数据源,数据集可以是表.特征类.关系类 ...

  10. 想转行做程序员,目前想学WEB前端,想问该自学还是报培训班

    首先我们还是先看一下WEB前端目前的工资情况吧,我在IT招聘网站拉勾网来进行搜索1-3年WEB前端工作经验大专学历的条件来看. 深圳: 可以看出目前深圳的平均的工资都在10K以上,因为大城市给的机会多 ...