python 05—字典

一、字典的唯一

键:简单对象,例【字符串、整数、浮点数、bool值】

list不能作为键,但可以作为值。

例:

score = {

    '萧峰' : 95,

    '段誉' : 97,

    '虚竹' : 89

}

python字典中的键/值对没有顺序,无法用索引访问字典的某一项,而要用键来访问。

print score['段誉']

字符串加引号,数字不用

字典也可以通过for . . . in遍历【遍历中存储的是字典的键】:

for name in score :

print score[name]

若要改变某一项的值,就直接赋值

例:

score ['虚竹'] = 91

增加一项字典项的方法,给一个新建赋值

score ['慕容复'] = 88

删除一项字典的方法是del键必须存在字典中

del score['萧峰']

新建一个空字典:

d = {}

>>> score = {'萧峰':95, '虚竹':97, '段誉' :89}
>>> print score['段誉']
89
>>> for name in score:
... print score[name]
... score['虚竹'] = 91
File "<stdin>", line 3
score['虚竹'] = 91
^
SyntaxError: invalid syntax
>>> score['虚竹'] = 91
>>> score['慕容复'] = 91
>>> del score['萧峰']
>>> for name in score:
... print name, score[name]
...
虚竹 91
慕容复 91
段誉 89

二、函数的默认参数

猜你喜欢

转载自www.cnblogs.com/bwling/p/9122096.html