Python Dictionary 笔记

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值