|
>>> d = { " server " : " mpilgrim " , " database " : " master " }
>>> d
{ ' server ' : ' mpilgrim ' , ' database ' : ' master ' }
>>> d[ " server " ]
' mpilgrim '
>>> d[ " database " ]
' master '
>>> d[ " mpilgrim " ]
Traceback (innermost last):
File " <interactive input> " , line 1 , in ?
KeyError: mpilgrim
1、每一个dictionary中的每一个item就是一对值:key-value。可以通过key引用value,但不能通过value引用key。
2、每一个key是大小写敏感的
3、给一个dictionary添加一个新item:dictName[newKey] = newValue。如果newKey存在,则newValue会覆盖原来的value。这也表明添加、修改item用的是相同的语法。
4、value的类型可以是任意的,同一个dictionary中的value的类型并不需要一致。key的类型必须是所有不可变的类型,tuple有时也可以作为key,这时候tuple不能包含可变类型,不管是直接包含还是间接包含。
5、del D[k]删除一个key是k的item。
6、操作 k in D 可以用来检查key
k 是否包含在D的所有keys中
7
Dictionary object methods
Method
Description
Nonmutating methods
D
.copy( )
Returns a shallow copy of the dictionary (a copy whose items
are the same objects as D
's, not copies thereof)
D
.has_key(
k
)
Returns TRueif k
is a key in
D
; otherwise, returns False
, just like
k
in
D
D
.items( )
Returns a new list with all items (key/value pairs) in
D
D
.keys( )
Returns a new list with all keys in
D
D
.values( )
Returns a new list with all values in
D
D
.iteritems( )
Returns an iterator on all items (key/value pairs) in
D
D
.iterkeys( )
Returns an iterator on all keys in
D
D
.itervalues( )
Returns an iterator on all values in
D
D
.get(
k
[,
x
])
Returns D
[
k
]if k
is a key in D
; otherwise, returns
x
(or None
, if x
is not
given)
Mutating methods
D
.clear( )
Removes all items from D
, leaving
D
empty
D
.update(
D1
)
For each k
in D1
, sets
D
[
k
]equal to
D1
[
k
]
D
.setdefault(
k
[,
x
])
Returns D
[
k
]if k
is a key in D
; otherwise, sets
D
[
k
]equal to
x
and returns x
D
.pop(
k
[,
x
])
Removes and returns
D
[
k
]if k
is a
key in D
; otherwise, returns x
(or raises an
exception if x
is not given)
D
.popitem( )
Removes and returns an arbitrary item (key/value pair)
|
|
|