python字典的get函数和iteritems函数

来源:互联网 发布:界面汉化软件 编辑:程序博客网 时间:2024/06/04 18:24

1.get()

当我们获取字典里的值的时候,一个是通过键值对,即dict['key'],另一个就是dict.get()方法。

例如:

>>> dict = {'a':'AA', 'b':'BB', 'c':'CC'}>>> dict['a']'AA'>>> dict.get('a')'AA'

get()方法语法:
dict.get(key, default=None)

key -- 字典中要查找的键。
default -- 如果指定键的值不存在时,返回该默认值。

例如:

>>> dict.get('d','error')'error'

2.iteritems()

python字典中还存在items()方法。两者有些许区别。

items方法是可以将字典中的所有项,以列表方式返回。
iteritems方法与items方法相比作用大致相同,只是它的返回值不是列表,而是一个迭代器。

>>> d = {'1':'one', '2':'two', '3':'three'}>>> x = d.items()>>> x[('1', 'one'), ('3', 'three'), ('2', 'two')]>>> type(x)<type 'list'>>>> y = d.iteritems()>>> y<dictionary-itemiterator object at 0x025008A0>>>> type(y)<type 'dictionary-itemiterator'>


0 0
原创粉丝点击