dict
字典的用法,dict的查找特别快捷。如果我们的项目经常用到搜索某些数据,最好用dict类型。
创建dict
或者
1
2
| >>> dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}
|
或者用dict构造函数创建dict变量
1
| dict2 = dict([(key1, value1),(key2,value2),...]
|
表达式创建
1
2
| >>> dict3 = {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
|
添加元素
1
2
3
4
5
| tel = {}
#dict1[key] = value
tel['guido'] = 4127
tel['jack'] = 4098
tel['sape'] = 4193
|
获取元素值
如果键不存在,tel[key]操作会出错,所以在获取元素之前,需要判断元素键是否存在
判断方法?
1
2
| if tel.get("snape"):
num1 = tel["snape"]
|
或者
1
2
| if "snape" in tel:
num1 = tel["snape"]
|
删除元素
1
2
| del tel["guido"]
#tel.pop("jack")
|
遍历
迭代器:
1
2
3
4
5
6
| >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
|