Python Dictionary 笔记
等同于 JAVA 的 map
无序
创建
>>> eng2sp = dict()
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
>>> print eng2sp
{}
添加 key value
>>> eng2sp['one'] = 'uno'
>>> print eng2sp
{'one': 'uno'}
检查 key 是否在 dictionary 中
>>> 'one' in eng2sp
True
>>> 'uno' in eng2sp
False
通过 key 获取 value
如果 key 不存在, 会导致 error
>>> print eng2sp['two']
'dos'
get(key, defaultValue)
方法获取value
如果 key 存在, 则返回对应的 value
如果 key 不存在, 则返回参数中的 defaultValue (这样就不会报错了)
>>> h = histogram('a')
>>> print h
{'a': 1}
>>> h.get('a', 0)
1
>>> h.get('b', 0)
0
测量 pair 数量
>>> len(eng2sp)
3
获取全部 keys
返回一个无序 list
>>> vals = eng2sp.keys()
获取全部 values
返回一个 list
>>> vals = eng2sp.values()
什么是 hash, 为什么 dictionary 的 key 必须是 hashable 的
key 可以是 tuple, 但不可是 list
A hash is a function that takes a value (of any kind) and returns an integer. Dictionaries use these integers, called hash values, to store and look up key-value pairs.
This system works fine if the keys are immutable. But if the keys are mutable, like lists, bad things happen. For example, when you create a key-value pair, Python hashes the key and stores it in the corresponding location. If you modify the key and then hash it again, it would go to a different location. In that case you might have two entries for the same key, or you might not be able to find a key. Either way, the dictionary wouldn’t work correctly.
dictionary 变 tuple
items() 方法
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]
tuple 可以作为 dictionary 的 key
firstName = "Goudan"
lastName = "Li"
telephoneNumber = 123456789
dictioanry[firstName, lastName] = telephoneNumber
复制 dictioanry
dict.copy()
这个是 shallow copy, 不是 deep copy