1. Dictionaries
A, the dictionary can be understood as a mapping, is a correspondence, called key-value correspondence, such as key: name corresponding value: Sola, dictionary: {Name:sola}
Similarly, like sequences, tuples, dictionaries also have their generating functions dict
As follows:
>>> a = [(' Name ', ' Sola '), (' Phonenum ', ' 123456 ')]
>>> B = Dict (a)
>>> b
{' Phonenum ': ' 123456 ', ' name ': ' Sola '}
>>> b[' name ']
' Sola '
>>> b[' Phonenum ']
' 123456 '
B, the method of the dictionary:
Clear #清除字典中所有的项
>>> b
{' Phonenum ': ' 123456 ', ' name ': ' Sola '}
>>> B.clear ()
>>> b
{} #返回一个空字典
Copy #返回具有相同键值对的字典
>>> b
{' Phonenum ': ' 123456 ', ' name ': ' Sola '}
>>> C = b.copy ()
>>> C
{' Phonenum ': ' 123456 ', ' name ': ' Sola '}
Fromkeys #使用给定的键, create a new dictionary with each key corresponding to a default value of None
>>> C = {}.fromkeys ([' Name ', ' class '])
>>> C
{' name ': None, ' class ': none}
>>> c[' name '] = ' sola '
>>> C
{' name ': ' Sola ', ' class ': None}
Get #用于访问字典中的项, even if the item does not exist, can also customize the default return value
>>> C
{' name ': ' Sola ', ' class ': None}
>>> c.get (' name ')
' Sola '
>>> c.get (' home ')
>>> c.get (' home ', ' Meizhou ')
' Meizhou '
Has_key #检查字典中是否含有特定的键. Similar member methods
>>> C
{' name ': ' Sola ', ' class ': None}
>>> c.has_key (' name ')
True
>>> C.has_key (' home ')
False
Items,iteritems #items Returns all entries in the dictionary as a list, each item in the list is (key, value) pair, Iteritems returns an iterator object (which can be understood as returning all the entries in the dictionary as a collection, not as one item in the list)
>>> b
{' Phonenum ': ' 123456 ', ' name ': ' Sola '}
>>> B.items ()
[(' Phonenum ', ' 123456 '), (' Name ', ' Sola ')]
>>> B.iteritems ()
<dictionary-itemiterator Object at 0x022d5660>
>>> items = B.iteritems ()
>>> for item in items:
.... Print item
...
(' Phonenum ', ' 123456 ')
(' name ', ' Sola ')
Keys,iterkeys #keys将字典中的键以列表的形式返回, and Iterkeys returns an iterator for the key
Values,itervalues #values将字典中的值以列表的形式返回, Itervalues returns an iterator for the value
>>> B.keys ()
[' Phonenum ', ' name ']
>>> b.values ()
[' 123456 ', ' sola ']
Update #可以利用一个字典项更新另外一个字典项
>>> b
{' Phonenum ': ' 123456 ', ' name ': ' Sola '}
>>> C
{' Home ': ' Meizhou ', ' country ': ' China '}
>>> B.update (c)
>>> b
{' name ': ' Sola ', ' country ': ' China ', ' home ': ' Meizhou ', ' phonenum ': ' 123456 '}
Python Learning notes list, tuples, dictionaries (2)