python学习(1)-字典 (Dictionary)
字典(Dictionary)是一种映射结构的数据类型,由无序的“键-值对”组成。字典的键必须是不可改变的类型,如:字符串,数字,tuple;值可
以为任何python数据类型。
1、新建字典
>>> dict1={}
#建立一个空字典
>>> type(dict1)
<type 'dict'>
2、增加字
典元素:两种方法
>>> dict1['a']=1 #第一种
>>> dict1
{'a':
1}
#第二种:setdefault方法
>>> dict1.setdefault('b',2)
2
>>>
dict1
{'a': 1, 'b': 2}
3、删除字典
#删除指定键-值对
>>>
dict1
{'a': 1, 'b': 2}
>>> del dict1['a']
#也可以用pop方法,dict1.pop('a')
>>> dict1
{'b': 2}
#清空字典
>>>
dict1.clear()
>>> dict1 #字典变为空了
{}
#删除字典对象
>>>
del dict1
>>> dict1
Traceback
(most recent call last):
File "<interactive input>", line
1, in <module>
NameError: name 'dict1' is not defined
4、字典的方法
1)get(key,default=None)
返回键值
key
对应的值;如果
key
没有在字典里,则返回
default
参数的值,默认为
None
>>>
dict1 #空的字典
{}
>>> dict1.get('a')
#键‘a’在dict1中不存在,返回none
>>> dict1.get('d1','no1')
#default参数给出值'no1',所以返回'no1'
'no1'
>>> dict1['a']='no1'
#插入一个新元素
>>> dict1
{'a': '1111'}
>>>
dict1.get('a') #现在键'a'存在,返回其值
'1111'
2)clear
清空字典
3)has_key(key)
如果
key
出
现在
dict
里则返回
True
;否则返回
False
>>> dict1
{'a':
'1111'}
>>> dict1.has_key('b')
False
>>>
dict1.has_key('a')
True
4)items
返回
dict
的(键,值)tuple对的一个列表
>>> dict1
{'a': 'no1', 'b': '2222'}
>>>
相关文档:
#==================================================
import wx
import wx.media
class MyFrame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self,parent,-1,title,pos=(150,150),size&;nbsp;=(640, 480),style=wx.MAXIMIZE_BOX|wx.SYSTEM_MENU|wx.CAPTION|wx.CLOSE_BOX| ......
Example 2-18 展示了 traceback 模块允许你在程序里打印异常的跟踪返回
(Traceback)信息, 类似未捕获异常时解释器所做的. 如 Example 2-18 所示. 2.11.0.1. Example
2-18. 使用 traceback 模块打印跟踪返回信息 File: traceback-example-1.py # note!
import
Example 2-18 展示了 traceback 模块允许你在程序里打印异常 ......
以前也写过一些关于 vim 环境变量的内容,使用 vim 和 python ,每一段时间后都会有新的体会,所以要不断总结了.
vim 针对 python 的万能补全: vim 当前进程需要找到相应补全模块库所在位置,此是就和 python 的path环境变量相关。
python 代码运行时: 对于import 的模块也需要确定它的具体位置,python 解释器会到当前路 ......
正则表达式是搜索、替换和解析复杂字符模式的一种强大而标准的方法.
正则表达式(或 RE)是一种小型的、高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现.字符串也有很多方法,可以进行搜索 (index、find 和 count)、替换 (replace) 和解
析 (split),但它们仅限于处理最简单的情况
re 模块使 P ......
1. What’s the difference between all of the os.popen() methods?
popen2 doesn't capture standard error, popen3 does capture standard
error and gives a unique file handle for it. Finally, popen4 captures
standard error but includes it in the same file object as standard
output.
os.popen()&n ......