现在在实习期间,好久没用Python了,今天在做Java项目时用的HashMap让我联想到了Python中的字典,就写一些Python字典的知识吧,复习复习。

字典:  key --> value的映射关系,字典是无序性的,字典的key是不可变类型的,如int, str, float,tuple...

1.创建字典

(1)第一种方式创造字典,一次给全

>>> user = {'}
>>> user
{', 'id': 1000, 'name': 'scd'}

(2)d[key] = value

>>> user = { }
>>> user['id'] = 1000
>>> user['name'] = 'scd'
>>> user['
>>> user
{', 'id': 1000, 'name': 'scd'}
>>>

(3)d = dict(zip(key, value)),   这里key, value是列表,列表并不是字典的key,字典的key为列表中的某一项

>>> key = ['id', 'name', 'password']
>>> value = [1000, ']
>>> user = dict(zip(key, value))
>>> user
{', 'id': 1000, 'name': 'scd'}
>>>

第2种创建字典的方法经常用到

2.字典遍历

>>> for key in user:
...     print key, ":", user[key]
...
password : 123
id : 1000
name : scd
>>>

经常使用的是创建字典的第(2)种方式和字典的遍历

3.字典方法

(1)has_key 返回True或者False

>>> user = {}
>>> user[
>>> user['name'] = 'scd'
>>> user['
>>> user
{, 'name': 'scd'}
>>> help(user.has_key)
Help on built-in function has_key:

has_key(...)
    D.has_key(k) -> True if D has a key k, else False

>>> user.has_key('id')
True
>>>

(2)items  返回列表

>>> help(user.items)
Help on built-in function items:

items(...)
    D.items() -> list of D's (key, value) pairs, as 2-tuples

>>> user.items()
[('), ('id', 1000), ('name', 'scd')]
>>>

(3)iteritems 返回迭代器对象

>>> help(user.iteritems)
Help on built-in function iteritems:

iteritems(...)
    D.iteritems() -> an iterator over the (key, value) items of D

>>> user.iteritems()
<dictionary-itemiterator object at 0x0348E9F0>
>>>

(4)get 返回字典中的value值,如果不存在,则返回None

>>> help(user.get)
Help on built-in function get:

get(...)
    D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.

>>> user.get('id')
1000
>>> user.get('email')
>>> print user.get('email')
None
>>>