Example 3.1 Defining a Dictionary
>>>
?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 TRue if k is a key in
D; otherwise, returns False, just like
kinD |
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) |