Python数据结构之映射(內建字典)

来源:互联网 发布:发泥推荐 知乎 编辑:程序博客网 时间:2024/05/17 07:16

 一、定义

        Python中映射是通过名字来应用值的一种数据结构。而字典是python中唯一內建的映射类型。字典由多个键及与其对应的值构成的键--值对(也称为项)组成。键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键--值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。键值在字典中没有特殊的顺序,是的,字典是无序的,但都是存在特定的键key下,而键key可以是任意的不可变类型,比如浮点型、字符串或元组等,键是唯一的,值可不唯一。空字典不包含任何项,由两个花括号表示:{}。

二、字典的基本操作

1、序列的很多操作在字典上同样适用。set d=dict,k=key。

len(d),返回d中项的数量。

d[k],返回关联到键k上的值。

d[k] = v,将v关联到键k上。

del d[k],删除键为k的项。

k in d,检查d中是否包含有键为k的项。在字典中查键的成员资格比在列表中检查值的成员资格效率更高。

2、dict()

        可以用dict()通过其他映射或(键--值)对的序列建立字典。

>>> items = [('name','xiaoming'),('score',89)]>>> d = dict(items)>>> d{'score': 89, 'name': 'xiaoming'}
        也可以用dict()通过关键字参数来创建字典。

>>> d = {}>>> d{}>>> d = dict(name = 'xiaoming',score = 89)>>> d{'score': 89, 'name': 'xiaoming'}

3、字典的格式化字符串

        在每个转换说明符中的%字符后面加上键,该键用()括起来,后面再跟上其它说明元素,此时转换说明符还是像以前一样的工作。前提是,所给出的键,在字典中都要能找得到。

>>> phonebook = {'xiaoming':'1230','xiaohong':'0123','liqin':'0234'}>>> print "liqin's phone number is %(liqin)s." % phonebookliqin's phone number is 0234.>>> 
        还可以利用模板批量转换任意数量的字符串。

>>> bookstore = {'COOKING':{'language':'cn','author':'xiaoming','year':2017,'price':20},'CODING':{'language':'cn','author':'xiaohong','year':2016,'price':40},'PYTHON':{'language':'cn','author':'liqin','year':2015,'price':60}}>>> template = '''<XML bookstore><book category XX>    <title %(language)s</title>    <author> %(author)s</author>    <year> %(year)s</year>    <price> %(price)s</price></book><XML bookstore>'''>>> from copy import deepcopy>>> booktype = raw_input('please in put book type: ')please in put book type: coding>>> booktype.upper()'CODING'>>> dct = deepcopy(bookstore[booktype])Traceback (most recent call last):  File "<pyshell#8>", line 1, in <module>    dct = deepcopy(bookstore[booktype])KeyError: 'coding'>>> booktype = booktype.upper()>>> dct = deepcopy(bookstore[booktype])>>> type(dct)<type 'dict'>>>> type(template)<type 'str'>>>> print bookstore{'PYTHON': {'price': 60, 'year': 2015, 'language': 'cn', 'author': 'liqin'}, 'COOKING': {'price': 20, 'year': 2017, 'language': 'cn', 'author': 'xiaoming'}, 'CODING': {'price': 40, 'year': 2016, 'language': 'cn', 'author': 'xiaohong'}}>>> print dct{'price': 40, 'author': 'xiaohong', 'language': 'cn', 'year': 2016}>>> print template<XML bookstore><book category XX>    <title %(language)s</title>    <author> %(author)s</author>    <year> %(year)s</year>    <price> %(price)s</price></book><XML bookstore>>>> print template % dct<XML bookstore><book category XX>    <title cn</title>    <author> xiaohong</author>    <year> 2016</year>    <price> 40</price></book><XML bookstore>>>> 
4、自动添加项

        一个字典中即使键期初不存在,但需要给它付个值,这时可以直接赋值,不需要初始化或使用append等方法去赋值。

>>> d = {}>>> d[3] = 'xiaoming'>>> d{3: 'xiaoming'}>>> d[0] = 'xiaohong'>>> d{0: 'xiaohong', 3: 'xiaoming'}>>> d[1] = 'liqin'>>> d{0: 'xiaohong', 1: 'liqin', 3: 'xiaoming'}>>> 
三、字典方法

1、clear()

        clear方法用于清空字典中的所有的项,该方法没有返回值。

>>> d{0: 'xiaohong', 1: 'liqin', 3: 'xiaoming'}>>> d.clear()>>> d{}>>> 
2、copy()、deepcopy(x)

        copy是浅拷贝,返回具有相同项的新字典。

>>> d1 = dict(name = 'xiaoming',ID = '00001',age = 13,score = [80,78,99,96])>>> d2 = d1.copy()>>> d1{'age': 13, 'score': [80, 78, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d2{'age': 13, 'score': [80, 78, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d2['age'] = 12>>> d1{'age': 13, 'score': [80, 78, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d2{'age': 12, 'score': [80, 78, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d2['score'].remove(78)>>> d1{'age': 13, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d2{'age': 12, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> 

        deepcopy(x)是深拷贝。

>>> from copy import deepcopy>>> d3 = deepcopy(d1)>>> d1{'age': 13, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d3{'age': 13, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d3['score'].append(78)>>> d1{'age': 13, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d3{'age': 13, 'score': [80, 99, 96, 78], 'ID': '00001', 'name': 'xiaoming'}>>> 
3、fromkeys()

        fromkeys方法是使用指定的键创建一个新的字典,且每个键的值赋值为None。

>>> d4 = dict.fromkeys(['name','ID','age'])>>> d4{'age': None, 'name': None, 'ID': None}>>>
4、get()

        get方法是一种更为宽松的访问字典项的方法,当用索引访问一个不存在的键时,会报语法错误,但是当用get方法访问一个不存在的键不会报错,它会返回None。

>>> d1{'age': 13, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d1['sex']Traceback (most recent call last):  File "<pyshell#64>", line 1, in <module>    d1['sex']KeyError: 'sex'>>> d1.get('sex')>>> print d1.get('sex')None>>> 

        如果键不存在,不想返回默认的None,那你还可以自己修改默认值,如替换为nonexistent。

>>> d1.get('sex','nonexistent')'nonexistent'>>> 

5、has_key()

        has_key方法用于检查字典中是否包含指定的键,有则返回True,没有则返回False。dct.has_key(k)相当于k in dct。注意Python 3.0版本没有这个函数。

>>> d1.has_key('name')True>>> d1.has_key('sex')False>>> 
6、items()和iteritems()

        items方法无序的将字典中的所有项按(键,值)形式返回。

        iteritems方法作用一样,但返回的是一个迭代器。

>>> d1{'age': 13, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d1.items()[('age', 13), ('score', [80, 99, 96]), ('ID', '00001'), ('name', 'xiaoming')]>>> itr = d1.iteritems()>>> for v in itr:print v('age', 13)('score', [80, 99, 96])('ID', '00001')('name', 'xiaoming')>>> 
7、keys()和iterkeys()

        keys方法无序的将字典中的所有键返回。

        iterkeys方法作用一样,但返回的是一个迭代器。

>>> d1{'age': 13, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> lst = d1.keys()>>> lst['age', 'score', 'ID', 'name']>>> itr = d1.iterkeys()>>> for v in itr:print vagescoreIDname>>> 

8、values()和itervalues()

        values方法无序的将字典中的所有值返回。

        itervalues方法作用一样,但返回的是一个迭代器。

>>> d1{'age': 13, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> lst = d1.values()>>> lst[13, [80, 99, 96], '00001', 'xiaoming']>>> itr = d1.itervalues()>>> for v in itr:print v13[80, 99, 96]00001xiaoming>>> 

9、pop()

        pop方法用于移除指定键的项,一定要指定一个键,返回指定键对应的值。

{'age': 13, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d1.pop('ID')'00001'>>> d1{'age': 13, 'score': [80, 99, 96], 'name': 'xiaoming'}>>> 
10、popitem()

        popitem方法用于随机移除字典里面的项,返回被移除的项(键,值),相当于list.pop(),但是list.pop()每次都是移除最后一项,字典是没有顺序概念的,所以是随机移除。

>>> d1{'age': 13, 'score': [80, 99, 96], 'name': 'xiaoming'}>>> d1.popitem()('age', 13)>>> d1{'score': [80, 99, 96], 'name': 'xiaoming'}>>>
11、setdefault()

        setdefault方法用来设置字典中键未存在(尚没有的项)的值,如果不指定值,默认值None,但只要执行了一次,键,就存在了,如果指定值,则返回该指定值。如果键存在了,则不修改键对应的值,且返回该键对应的值。所以setdefault通常用于获取指定键对应的值。

>>> d1{'score': [80, 99, 96], 'name': 'xiaoming'}>>> d1.setdefault('age')>>> d1{'age': None, 'score': [80, 99, 96], 'name': 'xiaoming'}>>> d1.setdefault('ID','nonexistent')'nonexistent'>>> d1{'age': None, 'score': [80, 99, 96], 'ID': 'nonexistent', 'name': 'xiaoming'}>>> d1.setdefault('sex','male')'male'>>> d1{'age': None, 'score': [80, 99, 96], 'sex': 'male', 'ID': 'nonexistent', 'name': 'xiaoming'}>>> d1.setdefault('sex','nonexistert')'male'>>> d1{'age': None, 'score': [80, 99, 96], 'sex': 'male', 'ID': 'nonexistent', 'name': 'xiaoming'}>>> di.setdefault('age',12)Traceback (most recent call last):  File "<pyshell#110>", line 1, in <module>    di.setdefault('age',12)NameError: name 'di' is not defined>>> d1.setdefault('age',12)>>> d1{'age': None, 'score': [80, 99, 96], 'sex': 'male', 'ID': 'nonexistent', 'name': 'xiaoming'}>>> 
12、update()

        update方法可以利用一个字典项去更新另外一个字典,提供的字典中的项会被添加到旧字典中,如果有相同的键则会进行覆盖。

>>> d1{'age': 13, 'score': [80, 99, 96], 'ID': '00001', 'name': 'xiaoming'}>>> d = {'sex':'male','age':14}>>> d1.update(d)>>> d1{'score': [80, 99, 96], 'name': 'xiaoming', 'age': 14, 'ID': '00001', 'sex': 'male'}>>> 








阅读全文
0 0
原创粉丝点击