转载自:http://www.xwy2.com/article.asp?id=112
Python 中的 Dictionary 和 .NET Hashtable / Dictionary 非常类似。
Code
>>>>>> a = {1:"a", 2:"b"}
>>>>>> a[1]
'a'
>>>>>> b = {'a':100, 'b':200}
>>>>>> b[2]
Traceback (most recent call last):
File "<pyshell#93>", line 1, in <module>
b[2]
KeyError: 2
>>>>>> b['b']
200
>>>>>> a[1]='aaa'
>>>>>> a
{1: 'aaa', 2: 'b'}
>>>>>> del(a[1])
>>>>>> a
{2: 'b'}
>>>>>> a[1]='AAAA'
>>>>>> a
{1: 'AAAA', 2: 'b'}
>>>>>> a.has_key(1)
True
>>>>>> a.keys()
[1, 2]
>>>>>> a.values()
['AAAA', 'b']
>>>>>> a.items()
[(1, 'AAAA'), (2, 'b')]
>>>>>>
Dictionary 的 key 是大小写敏感的。
Code
>>>>>> b = {"a":1, "A":2}
>>>>>> b["A"]
2
>>>>>> b["a"]
1
>>>>>>
可以使用 Get() 方法避免触发 KeyError。
Code
>>>>>> b={'a':1,'A':2}
>>>>>> b['c']
Traceback (most recent call last):
File "<pyshell#112>", line 1, in <module>
b['c']
KeyError: 'c'
>>>>>> b.get('c')
>>>>>> b.get('c','default')
'default'
>>>>>>