python字典(dictionary)中get和items、iteritems方法
2018-02-27 10:50
651 查看
dictionary
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。值得注意的是,由于一个key只能对应一个value,所以,多次对一个key放入value,后面的值会把前面的值覆盖。
#dict的初始化 key-value >>>dic = {‘1’:‘one’,2:'two','3':'three'}
取出字典中的值 与get函数
一般的我们可以通过key来获取对应的value,但是也可以使用get函数。其中get函数原型为dict.get(key, default=None),
参数说明:
key – 字典中要查找的键。
default – 如果指定键的值不存在时,返回该默认值值。默认为None,也可以指定其他值。
返回值:
返回指定键的值,如果值不在字典中返回默认值None。
# 访问的key都存在时,并没有什么区别 # 'one' >>>dic['1'] # 'one' >>>dic.get('1','No') #访问的key不存在的时候,就有区别了,get能使程序继续运行下去,而直接通过key访问的方#法会报错 >>>dic['women'] # None >>>print dic.get('women') #meiyou >>>print dic.get('womne','meiyou')
items与iteritems
items方法是可以将字典中的所有项,以列表方式返回。也就说将字典转成了list。iteritems方法与items方法相比作用大致相同,只是它的返回值不是列表,而是一个迭代器。至于为什么要转为迭代器,当然是为了迭代访问字典中的元素。而且由于iteritems是就地转为迭代器的,不同于items会返回一个全新的列表,所以不会消耗额外空间。
>>> dic = {'1':'one', '2':'two', '3':'three'} >>> x = dic.items() >>> x [('1', 'one'), ('3', 'three'), ('2', 'two')] >>> type(x) <type 'list'> >>>type(x[0]) <type 'tuple'> # 使用iteritems方法 >>> y = d.iteritems() >>> type(y) <type 'dictionary-itemiterator'> >>> y <dictionary-itemiterator object at 0x7f70f4ec9890> # 与下面一节的访问key-value比较一下就可以看出其中的不同了 >>> type(dic) <type 'dict'> # 【注意使用了iteritems方法之后】 >>> dic2 = dic.iteritems() >>> type(dic2) <type 'dictionary-itemiterator'> # 将dic转为迭代器之后,直接就可以迭代dic2内的元素了 >>> for k,v in dic2: ... print k," = == =",v ... 1 = == = one 3 = == = three 2 = == = two
字典的迭代
顺便提一下字典的迭代。# 1. 迭代字典的key # 1)方法1 >>> for x in dic.keys(): ... print x ... 1 3 2 # 2) 方法2 >>> for x in dic.iterkeys(): ... print x ... 1 3 2 #2. 迭代字典的value # 1)方法1 >>> for v in dic.values(): ... print v ... one three two # 2)方法2 >>> for v in dic.itervalues(): ... print v ... one three two #迭代key-vlaue对 # 迭代键值对 >>> for k,v in dic.items(): ... print k,":",v ... 1 : one 3 : three 2 : two >>>for k, v in d.iteritems(): ... print k, ":", v
相关文章推荐
- Python 字典(Dictionary) items()方法
- Python 字典(Dictionary) get()方法
- Python 字典(Dictionary) get()方法
- 1006- Python 字典(Dictionary) items()方法
- Python 字典(Dictionary) get()方法
- python 字典 get(),items(),iteritems()方法
- Python 字典(Dictionary) get()方法
- Python 字典(Dictionary) get()方法
- Python 字典(Dictionary) get()方法
- Python 字典(Dictionary) get()方法
- Python 字典(Dictionary) get()方法
- Python 字典(Dictionary) get()以及operator.itemgetter函数
- python 字典 get方法
- Python 字典items返回列表,iteritems返回迭代器
- Python的字典get方法:从字典中获取一个值
- Python3字典中items()和python2.x中iteritems()有什么区别
- Python3 字典 get() 方法
- Python中使用items()方法返回字典元素对的教程
- Python 字典(Dictionary) keys()方法
- Python中使用items()方法返回字典元素对的教程