python学习笔记18:字典dict
使用help(dict)获取完整方法列表;
字典赋值
>>> addr_book = {‘Swa’:’swa@123.com’, ’Larry’:’larry@124.com’ ,’Mat’:’mat@125.com’,’Spa’:’spa@126.com’}
获取key对应的value
>>> addr_book[‘Swa’] # 返回值为key对应的value
‘swa@123.com’
>>> addr_book.get(‘xxx’, -1) #使用get(),-1是指定(在key不存在时)的返回值
-1
添加一对key:value:
```python
>>> addr_book[‘Gui’] = ‘gui@127.com’
删除一对key:value
>>> addr_book.pop(‘Spa’) # 返回值为value
‘spa@126.com’
获取字典的k:v对数/key的个数
>>> len(addr_book)
4
添加多对key:value:
>>> addr_book.update({k0:v0, k1:v1})
>>>
遍历字典:
>>> # 迭代dict中的k-v对
>>> for name, addr in addr_book.items():
... print ‘%s : %s’%(name, addr)
...
>>> # 迭代dict中的key, 也可以用addr_book.keys()
>>> for name in addr_book:
... addr = addr_bood[name]
... print ‘%s : %s’%(name, addr)
...
>>> # 迭代 dict中的value
>>> for addr in addr_book.values():
... print ‘%s’%( addr)
...
判断key是否存在:
>>> ‘Swa’ in addr_book
True
字典中的key是无序的,如果需要key有序,可以使用collections.OrderedDict()
对dict的操作都可以用在OrderedDict上
>>> import collections
>>> d0 = collections.OrderedDict()
>>> d0['a'] = 0
>>> d0['c'] = 2
>>> d0['b'] = 1
>>> d0['d'] = 3
>>> d0
OrderedDict([('a', 0), ('c', 2), ('b', 1), ('d', 3)])
>>>