1.前言

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

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

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

2.定义字典

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

dic = { 'name' : 'nanliangrexue','age':18}
print(dic)
#输出
{'name': 'nanliangrexue', 'age': 18}

3.字典的增删改查

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

dic = { 'name' : 'nanliangrexue','age':18}
dic['gender'] = 'male'
print(dic)
#输出
{'name': 'nanliangrexue', 'age': 18, 'gender': 'male'}

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

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

dic = { 'name' : 'nanliangrexue','age':18}
dic['age'] = 28
print(dic)
#输出
{'name': 'nanliangrexue', 'age': 28}

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

4.字典的方法

  • dict.fromkeys(键,值)

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

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

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

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

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

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

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

5.字典的遍历

  • 遍历字典的key
dic = { 'name' : 'nanliangrexue','age':18}
for key in dic.keys():
print(key)
#输出
'name'
'age'
  • 遍历字典中的value
dic = { 'name' : 'nanliangrexue','age':18}
for value in dic.values():
print(value)
#输出
'nanliangrexue'
18
  • 同时遍历字典中的key和value,以元组形式返回
dic = { 'name' : 'nanliangrexue','age':18}
for item in dic.items():
print(item)
#输出
('name', 'nanliangrexue')
('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. MySQL日期和时间类型笔记

    最近在看<MySQL技术内幕:SQL编程>并做了笔记,这是一篇笔记类型博客,分享出来方便自己复习,也可以帮助其他人 一.日期时间类型所占空间对比 各种日期时间数据类型所占的空间: 类型 所 ...

  2. tomcat容器是如何创建servlet类实例

    当容器启动时,会读取在webapps目录下所有的web应用中的web.xml文件,然后对xml文件进行解析,并读取servlet注册信息. 然后,将每个应用中注册的servlet类都进行加载,并通过反 ...

  3. Kubernetes中的PV和PVC是啥

    K8S引入了一组叫作Persistent Volume Claim(PVC)和Persistent Volume(PV)的API对象,大大降低了用户声明和使用持久化Volume的门槛. 在Pod的Vo ...

  4. LeetCode 300. Longest Increasing Subsequence最长上升子序列 (C++/Java)

    题目: Given an unsorted array of integers, find the length of longest increasing subsequence. Example: ...

  5. lua多线程解决方案

    直观的讲:lua并不支持多线程,lua语言本身具有携程功能,但携程仅仅是一种中继器. lua多线程的目的:有并发需求时,共享一些数据. 例如使用lua写一个并发服务器.用户登陆之后,用户数据储存在lu ...

  6. Django与drf 源码视图解析

    0902自我总结 Django 与drf 源码视图解析 一.原生Django CBV 源码分析:View """ 1)as_view()是入口,得到view函数地址 2) ...

  7. PHP compact

    1.函数的作用:将变量转成数组 2.函数的参数: @params string $varname1 @params string $varname2 ... @params array $varnam ...

  8. Ubuntu 安装mysql & 自定义数据存储目录

    一.安装 apt-get install mysql-server 执行过程如下: root@duke:~# apt-get install mysql-server 正在读取软件包列表... 完成 ...

  9. ubuntu 虚拟机设置静态ip

    $ sudo vim /etc/network/interfaces auto ens33   # 使用的网络接口,之前查询接口是为了这里     iface ens33 inet static    ...

  10. Java中常用的四种线程池

    在Java中使用线程池,可以用ThreadPoolExecutor的构造函数直接创建出线程池实例,如何使用参见之前的文章Java线程池构造参数详解.不过,在Executors类中,为我们提供了常用线程 ...