集团站切换校区

验证码已发送,请查收短信

复制成功
微信号:togogoi
添加微信好友, 详细了解课程
已复制成功,如果自动跳转微信失败,请前往微信添加好友
打开微信
图标

学习文章

当前位置:首页 > >学习文章 > >

{人工智能}python编程之字典

发布时间: 2018-08-03 17:56:35

3.1     实验介绍

关于本实验

本实验主要介绍了 Python 字典的相关知识点和简单操作。​

3.1.1     实验目的

1.理解 Python字典的含义。

2.掌握和 Python字典相关的操作。

3.2   实验任务配置

3.2.1     概念知识

1.  Python 字典。字典这种数据结构有点像我们平常用的通讯录,有一个名字和这个名字对应的信息。在字典中,名字叫做“键”,对应的内容信息叫做“值”。字典是一个键/值对的集合

2.它的基本格式是(key 是键,alue 是值):

d    =   {key1 : value1,   key2: value2 }

3.键/值对用冒号分割,每个对之间用逗号分割,整个字典包括在花括号中。

4.关于字典的键要注意的是:键必须是唯一的;键只能是简单对象,比如字符串、整数、浮点数、bool 值。

​3.2.1     实验内容

步骤 1   创建字典

有以下几种方式创建一个字典:

>>>a = {'one': 1, 'two': 2, 'three': 3}

>>>print(a)

{'three':3, 'two': 2, 'one': 1}

>>>b = dict(one=1, two=2, three=3)

>>>print(b)

{'three':3, 'two': 2, 'one': 1}

>>>c = dict([('one', 1), ('two', 2), ('three', 3)])

>>>print(c)

{'three':3, 'two': 2, 'one': 1}

>>>d = dict(zip(['one', 'two', 'three'], [1, 2, 3]))

>>>print(d)

{'three':3, 'two': 2, 'one': 1}

>>>e = dict({'one': 1, 'two': 2, 'three': 3})

>>>print(e)

{'one':1, 'three': 3, 'two': 2}

>>>print(a==b==c==d==e)

True

字典推导(dictcomp)

字典推导可以从任何以键值对作为元素的可迭代对象中构建出字典:

>>>data =[("John","CEO"),("Nacy","hr"),("LiLei","engineer")]

>>>employee = {name:work for name, work in data}

>>>print(employee)

{'LiLei':'engineer', 'John': 'CEO', 'Nacy': 'hr'}

字典查找

根据 key 值直接查找

>>>print(employee["John"]) 

CEO

如果字典中没有找到对应的 Key值,会抛出 KeyError:

>>>print(employee["Joh"]) Traceback (most recent call last):

File"<pyshell#13>", line 1, in <module>

print(employee["Joh"])

KeyError: 'Joh'

使用 dic[key]方法查找时,如果找不到对应的 key 值,会抛出异常,但是如果使用

dic.get(key,default)方法查找时,如果找不到对应的 key值,会返回默认值 default:

>>>print(employee.get("Nacy","UnKnown'")) 

hr

>>>print(employee.get("Nac","UnKnown"))

UnKnown





上一篇: {人工智能}python編程之字符串

下一篇: {人工智能}列表和元组

十五年老品牌
微信咨询:togogoi 咨询电话:18922156670 咨询网站客服:在线客服

相关课程推荐

在线咨询 ×

您好,请问有什么可以帮您?我们将竭诚提供最优质服务!