《Beginning Python From Novice to Professional》学习笔记六:Dictionary

全面掌握Python:从初学者到专业开发者的进阶之路(第3版) 本文还有配套的精品资源,点击获取 简介:《初识Python:从新手到专业(第3版)》是一本适合不同经验层次程序员的Python编程指南,涵盖了从基础知识到高级概念的完整学习路径。本书内容包括Python基础语法、面向对象编程、函数式编程、文件操作、网络编程、数据库集成、Web开发以及自动化任务等。同时,它还介绍了测试、调试、版本控制等软件开发的实践技能,以及大数据分析、机器... 阅读详情
1.创建(注意Dictionary是没有顺序的)
phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
冒号之前为key,之后为value,key必须具有唯一性。
items = [('name', 'Gumby'), ('age', 42)]
d = dict(items)
---> {'age': 42, 'name': 'Gumby'}
d = dict(name='Gumby', age=42)
---> {'age': 42, 'name': 'Gumby'}

2.Basic操作
len(dic)、d[key]、d[key] = val、del d[key]、key in dic
其中关于赋值要注意
x = {}
x[42] = 'Foobar'
---> {42: 'Foobar'}   #但在List中这样的操作是非法的,除非将x初始化为[None]*43

附上书上一段精致的示例:


---> Here is a sample run of the program:
Name: Beth
Phone number (p) or address (a)? p
Beth's phone number is 9102.


3.用Dictionary来格式化String
phonebook = {'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
"Cecil's phone number is %(Cecil)s." % phonebook
---> "Cecil's phone number is 3258."

一个实用的Dictionary在模板生成中的应用示例:
template = '''<html>
    <head><title>%(title)s</title></head>
    <body>
    <h1>%(title)s</h1>
    <p>%(text)s</p>
    </body>'''
data = {'title': 'My Home Page', 'text': 'Welcome to my home page!'}
print template % data
--->
<html>
<head><title>My Home Page</title></head>
<body>
<h1>My Home Page</h1>
<p>Welcome to my home page!</p>
</body>

#类似效果也可以用string.Template来实现

4.clear清空,无返回
returned_value = d.clear()
d
---> {}
print returned_value
---> None

5.copy复制(仔细对照下面两段代码)
x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
y = x.copy()
y['username'] = 'mlh'
y['machines'].remove('bar')
y
---> {'username': 'mlh', 'machines': ['foo', 'baz']}
x
---> {'username': 'admin', 'machines': ['foo', 'baz']}
#when you replace a value in the copy, the original is unaffected. if you modify a value, the original is changed as well because the same value is stored there. 归根到底是因为如果Value中用的是List,由于Python的引用性,实际存储的是List对象的地址,因此对Value的改变依然会影响前者。—— thy
改用copy库中的deepcopy函数可以改变,它将所有的引用处均作值拷贝
import copy
d = {}
d['names'] = ['Alfred', 'Bertrand']
c = d.copy()
dc = copy.deepcopy(d)
d['names'].append('Clive')
c
---> {'names': ['Alfred', 'Bertrand', 'Clive']}
dc
---> {'names': ['Alfred', 'Bertrand']}

6.fromkeys用给定的Keys创建新的Dictionary
{}.fromkeys(['name', 'age'])
---> {'age': None, 'name': None}
dict.fromkeys(['name', 'age'], 'thy')
---> {'age': 'thy', 'name': 'thy'}

7.get取值,但无如则返回一个特定的值而不会产生Exception
d = {}
print d.get('name')
---> None
d.get('name', 'N/A')   #用'N/A'代替默认的None
---> 'N/A'
d['name'] = 'Eric'
d.get('name')
---> 'Eric'
修改前面所示的例子:

--->
Name: Gumby
Phone number (p) or address (a)? batting average
Gumby's batting average is not available.


8.has_key指定的Key是否存在
d = {}
d.has_key('name')
---> False
d['name'] = 'Eric'
d.has_key('name')
---> True

9.items and iteritems
d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
d.items()
---> [('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]
#items返回一个由(key,value)的Tuple形式组成的无序List。
而iteritems会返回一个迭代器(Iterator)。

10.keys and iterkeys
d.keys()
---> ['url', 'spam', 'title']
#iterkeys同9所述

11.pop对key模仿栈操作
d = {'x': 1, 'y': 2}
d.pop('x')
---> 1
d
---> {'y': 2}

12.popitem对任一对(key,value)模仿栈操作
d = {'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
d.popitem()
---> ('url', 'http://www.python.org')
d
---> {'spam': 0, 'title': 'Python Web Site'}

13.setdefault类似于get方法
d = {}
d.setdefault('name', 'N/A')
---> 'N/A'
#这样在'name'未赋真正的值时默认为'N/A',一旦赋值后'N/A'便不存在了
d = {}
print d.setdefault('name')
---> None
#PS,setdefault会返回对默认值的引用,接上例看下面代码:
t=d.setdefault('sex', [])   #此时t成为其后[]的引用
t.append('F')
d   ---> {'name', 'N/A', 'sex': ['F']}

14.update更新已有key的value
d = {'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
x = {'title': 'Python Language Website'}
d.update(x)
d
---> {'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Language Website'}

15.values and itervalues
values返回由value组成的List(与keys不同的是,这样生成的List中可能会有相同值)
d.values()
---> ['http://www.python.org', 0, 'Python Language Website']
Beginning Python: From Novice to Professional 第二版 Gain a fundamental understanding of Python’s syntax and features with the second edition of Beginning Python, an up–to–date introduction and practical reference. Covering a wide array of Python–related programming topics, including addressing language internals, database integration, network programming, and web services, you’ll be guided by sound development principles. Ten accompanying projects will ensure you can get your hands dirty in no time. Updated to reflect the latest in Python programming paradigms and several of the most crucial features found in the forthcoming Python 3.0 (otherwise known as Python 3000), advanced topics, such as extending Python and packaging/distributing Python applications, are also covered. What you’ll learn * Become a proficient Python programmer by following along with a friendly, practical guide to the language’s key features. * Write code faster by learning how to take advantage of advanced features such as magic methods, exceptions, and abstraction. * Gain insight into modern Python programming paradigms including testing, documentation, packaging, and distribution. * Learn by following along with ten interesting projects, including a P2P file–sharing application, chat client, video game, remote text editor, and more. Complete, downloadable code is provided for each project! Who is this book for? Programmers, novice and otherwise, seeking a comprehensive introduction to the Python programming language. About the Apress Beginning Series The Beginning series from Apress is the right choice to get the information you need to land that crucial entry–level job. These books will teach you a standard and important technology from the ground up because they are explicitly designed to take you from “novice to professional.” You’ll start your journey by seeing what you need to know—but without needless theory and filler. You’ll build your skill set by learning how to put together real–world projects step by step. So whether your goal is your next career challenge or a new learning opportunity, the Beginning series from Apress will take you there—it is your trusted guide through unfamiliar territory! 立即下载

相关推荐

Beginning Python From Novice to Professional(3rd) 无水印pdf

Beginning Python From Novice to Professional(3rd) 英文无水印pdf 第3版 pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

《Beginning Python From Novice to Professional》学习笔记十二:__Magic__

1.属性访问class Rectangle: def __init__(self): self.width = 0 self.height = 0 def setSize(self, size): self.width, self.height = size #我的理解是自动组成Tuple def getS

thy专栏 970

Apress.Beginning.Python.From.Novice.to.Professional.3rd.Edition.

亲测很好,很新,很全的Python 入门学习资料(转点奶粉钱)

Beginning Python From Novice to Professional (3) - 列表操作

列表操作 list函数: >>> list('hello') ['h', 'e', 'l', 'l', 'o']改变列表: >>> x=[1,1,1] >>> x[1]=2 >>> x [1, 2, 1]删除元素: >>> names = ['wu','li','zhao','qian'] >>> del names[1] >>> names ['wu', 'zhao', 'qian']分

Marvin_wu 1203

Beginning Python from Novice to Professional 英文原版

虽然题目为python入门,并且全书逻辑性并不强,但是按着Hetland的篇目学习并且深究下来收获会很多的。楼主一狠心,这么好的英文原版书决定一点不要有志于学习python,加入python社区和开发行列的同志们资源费了。

Beginning Python From Novice To Professional(2rd Edition) (中文版)

Python开发教程,包含基本语法的说明及大量实例讲解,适合初级开发人员学习,可作为高级开发人员参考资料

Beginning Python: From Novice to Professional

Beginning Python: From Novice to Professional is the most comprehensive book on the Python ever written. Based on Practical Python, this newly revised book is both an introduction and practical refere

TopMVP 788

python基础教程(Beginning Python From Novice to Professional)书中源码例子

python基础教程 (Beginning Python From Novice to Professional) 书中源码例子

《Beginning Python From Novice to Professional》学习笔记八:Abstraction

Laziness Is a Virtue --- Real programmers are lazy. Not lazy in a bad way, but in the sense that they don’t do unnecessary work. 1.创建函数 def fibs(num): result = [0, 1] for i in range(num-2)

thy专栏 851

TwinCAT3与Matlab Simulink集成开发:如何快速生成和调试TcCOM模块

本文详细介绍了如何将TwinCAT3与Matlab Simulink进行深度集成,实现从控制算法模型到实时TcCOM模块的高效开发。通过环境搭建、模型配置、代码生成、系统集成与调试的完整流程,工程师可以快速将Simulink算法部署到倍福实时控制平台,大幅缩短开发周期并提升可靠性。

ik67890123的博客 224

接地设计的本质:按电流类型选择物理连接方式

接地是电子系统中实现电位参考、噪声抑制与安全保护的基础技术,其核心原理在于为不同性质的电流提供可控的低阻抗返回路径。从直流到GHz频段,电流的频率特性、能量等级和持续时间决定了接地的物理实现方式——工频安全电流依赖低电阻导体,高频噪声需低感平面或磁珠衰减,ESD脉冲要求受控泄放电阻,浪涌能量则必须通过独立短路径导入大地。这种‘目的决定方式’的设计逻辑,直接关联EMC合规性、信号完整性与系统可靠性。本文聚焦PCB级与设备级工程实践,详解安全地、功能地、浪涌地与静电地的判据差异及六种典型连接策略,帮助硬件工程师

weixin_36369848的博客 261

《Beginning Python From Novice to Professional》学习笔记七:Statement

1.More about Print print Age:, 42 ---> Age: 42 注意以下语句的区别: 1, 2, 3 ---> (1, 2, 3) print 1, 2, 3 ---> 1 2 3 print (1, 2, 3) ---> (1, 2, 3) 2.More about Import import somemodule from somemodule import

thy专栏 1248

全能扫描王的实现(python版本)- 目标检测图像矫正

全能扫描王python代码实现,可用于文件扫描或者是图像校正

搬砖猛女的啃书历程 5492

《Python基础教程(第三版)》阅读笔记

本文参考自《Beginning Python: from novice to professional》,中文版为《Python基础教程(第三版)》。

yyywxk的博客 612

【Unity+HoloLens2】从0开始在HoloLens2部署MR工程

HoloLens2部署的权威教程在微软的官方文档中,但有些问题其实官方文档并没有列出,所以在实际开发过程中如果遇到bug,就需要自身或者前人的经验去解决。比如:对于Hololens2来说,在VS中需选择ARM64而不是x86。部署需要有良好的网速;工程打包出来的文件路径和工程路径有关联,如果这两个路径不匹配,部署就会失败。部署后打不开可能是因为Unity中未添加需要部署的场景,在Build Settings中点击Add open Scenes。...

fmxs 4571

【实战指南】OpenClaw 使用 Bird Skill 接入 X(Twitter)的终极省心方案:告别每次都要手动喂 Cookie 的痛苦

OpenClaw 使用 Bird Skill 接入 X(Twitter)的终极省心方案:告别每次都要手动喂 Cookie 的痛苦

hampeter的博客 1802

这些年我读过的技术经典图书(附电子版下载地址)

本人大学期间专业是数学与应用数学, 2009年毕业, 学习不怎么样. 毕业后才开始接触计算机, 做过C开发, 系统运维和测试, 这4年我读了很多书, 电子书和纸质的, 这些书中有很多很经典的图书和资料, 现在拿来和大家分享一下. 每个资料都有下载衔接,大家可以直接下载, 都是免费的. C技术资料 1.> 作者: 谭浩强 这是我推荐的第一本书, 也是我接触的第一本书, 为什么把它

shitao827194819的专栏 2620

FPGA 学习笔记:Vivado 2020.2 MicroBlaze MIG 测试 DDR3 篇四

FPGA 学习笔记:Vivado 2020.2 MicroBlaze MIG 测试 DDR3 篇四

坚韧与专注 2163

Python基础教程

本书包括Python程序设计的方方面面,首先从Python的安装开始,随后介绍了Python的基础知识和基本概念,包括列表、元组、字符串、字典以及各种语句。然后循序渐进地介绍了一些相对高级的主题,包括抽象、异常、魔法方法、属性、迭代器。此后探讨了如何将Python与数据库、网络、C语言等工具结合使用,从而发挥出Python的强大功能,同时介绍了Python程序测试、打包、发布等知识。最后,作者结合

xiaotom5的专栏 1324

LLCC68芯片系统架构与LoRa驱动开发核心解析

LoRa射频收发器是低功耗广域物联网(LPWAN)的关键组件,其本质是集成了调制解调器、协议引擎、数据缓冲区与电源管理的专用SoC。理解其工作模式状态机(Sleep/Standby/TX/RX)与SPI主机接口时序规范,是实现稳定通信的基础。LLCC68通过寄存器映射与命令集双接口抽象硬件控制,支持LoRa扩频调制与FSK兼容模式,具备高链路预算(157 dB)和DC-DC/LDO动态电源切换能力。典型应用场景包括远距离传感器节点、智能表计与工业无线监测系统。本文深入剖析LLCC68的信号链路径、中断机制与

weixin_29859471的博客 284

24. SAP UI5 应用如何使用 OData 数据模型

本教程之前的二十三个步骤,使用的数据模型都是 JSON 模型。从本步骤开始,我们要学习另一种非常重要的数据模型:OData 数据模型。 OData 数据模型也是 SAP 产品里广泛使用的数据模型,比如 SAP S/4HANA,SAP CRM Fiori 应用等等,都使用的是 OData 数据模型而不是 JSON 数据模型。 使用 OData 数据模型的典型场景就是,通过 OData 模型提供的 Read API,将远端服务器上存储的数据通过 OData 协议读取到客户端,并显示在 SAP UI5 应用里。.

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 5798

Beginning Python From Novice to Professional (8) - 文件方法

文件方法 读写: #!/usr/bin/env python f = open('somefile.txt','w') f.write('Hello,') f.write('World!') f.close() f = open('somefile.txt','r') print f.read(5)Hello使用基本文件方法: #!/usr/bin/env python f = open(r

Marvin_wu 916

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

python3入门教程 pdf_Python基础教程第3版(Beginning Python From Novice to Professional 3th) pdf...

Magnus Lie Hetland又更新他的 "Beginning Python From Novice to Professional"了,该书为第三版英文,基于Python3.5进行讲解,紧跟技术潮流。希望对Python爱好者有所帮助。这是Python最新的介绍和实际参考。涵盖广泛的Python相关编程主题,包括语言处理、数据库集成、网络编程和Web服务,遵循良好的开发原则。十个配套项目可以...

weixin_39640911的博客 621

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

《Beginning Python From Novice to Professional》学习笔记五:Advanced String

1.格式化 format=hello, %s. Your ID is %d. values=(thy, 38) print format % values ---> hello, thy. Your ID is 38. 如第二句如示,要修饰多个元素,可以用Tuple,也可以用Dictionary(但不可以用List,因为List会被认为仅仅是一个单值) 2.模板(此功能不是内置的,因此

thy专栏 762

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

上一篇: 《Beginning Python From Novice to Professional》学习笔记五:Advanced String
下一篇: 《Beginning Python From Novice to Professional》学习笔记七:Statement
thy38
博客等级 码龄19年 184粉丝 116原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值