映射,字典是Python中唯一的内建的映射类型,字典中的值并没有特殊的顺序,但是都存储在一个特定的键(Key)里,

键可以是数字,字符串甚至元组


4.1 字典的使用:


加入有一个人名列表如下;

names=['Alice','Beth','Cecil','Dee-Dee','Earl']


如果要创建一个可以存储这些人的电话号码的小型数据库,应该怎么做呢?

一种方法是建立一个新的列表,假设只存储四位的分机电话号码,

那么可以得到于下面相似的列表:

numbers=['2341','9102','3158','0142','5551'];



names=['Alice','Beth','Cecil','Dee-Dee','Earl']

numbers=['2341','9102','3158','0142','5551'];

print numbers[names.index('Cecil')]



/*******************************
names=['Alice','Beth','Cecil','Dee-Dee','Earl']

numbers=['2341','9102','3158','0142','5551'];

print numbers[names.index('Cecil')]

print names[0];

print  [names.index('Cecil')]



C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
3158
Alice
[2]


4.2 创建和使用字典:


字典可以通过下面的方式创建:


phonebook={'Alice':'2341','Beth':'9102','Cecil':'3258'}

print phonebook

字典中键是唯一的



字典和列表访问方式:

字典访问方式:

phonebook={'Alice':'2341','Beth':'9102','Cecil':'3258'}

print phonebook

print phonebook['Alice']


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
{'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
2341


列表访问方式:

edward=['a1','b2','c3']
print edward[0];
print edward[1];
print edward[2];


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a5.py
a1
b2
c3

4.2.1  

可以使用dict 函数,通过其他映射(比如其他字典)或者(键,值) 这样的序列对建立字典:


items=[('name','Gumby'),('age',42)]
print items
d=dict(items)
print d
print d['name']


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
[('name', 'Gumby'), ('age', 42)]
{'age': 42, 'name': 'Gumby'}
Gumby


4.2.2 基本字典操作:

字典的基本行为在很多方面与序列(sequence)类似:

items = [('name', 'Gumby'), ('age', 42), ('k', 99)]
print items
d = dict(items)
print d
print d['name']

print len(d)
print d['k']

d['h']='001'
print d

print 'k' in d


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
[('name', 'Gumby'), ('age', 42), ('k', 99)]
{'k': 99, 'age': 42, 'name': 'Gumby'}
Gumby
3
99
{'k': 99, 'age': 42, 'name': 'Gumby', 'h': '001'}
True


>>> x=[]
>>> x[42]='aa'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range



字典示例:


people = {
    'Alice':{
        'phone':'2341',
        'addr':'foo drive 23'
    },
    'Beth':{
        'phone':'9102',
        'addr':'Bar street 42'
    },
    'Cecil':{
        'phone':'3158',
        'addr':'Baz avenue 90'

    }

}
print people
print people['Alice']['phone']


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a5.py
{'Beth': {'phone': '9102', 'addr': 'Bar street 42'}, 'Alice': {'phone': '2341', 'addr': 'foo drive 23'}, 'Cecil': 

{'phone': '3158', 'addr': 'Baz avenue 90'}}
2341


4.2.3  字典的格式化字符串:


4.2.4 字典方法:

1. clear

clear 方法清除字典中所有的项,这个是原地操作(类似于list.sort),所以无返回值(或者说返回None)

d={}
print d
d['name']='Gumby'
d['age']=42
print d
print d.clear()


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a6.py
{}
{'age': 42, 'name': 'Gumby'}
None


为什么这个方法有用呢? 考虑一下两种的情况,下面是第一种;


第一种情况:

C:\>python
Python 2.7.10 (default, May 23 2015, 09:40:32
Type "help", "copyright", "credits" or "licen
>>> x={}
>>> y=x
>>> x['key']='vale'
>>> y
{'key': 'vale'}
>>> x
{'key': 'vale'}
>>> x={}
>>> x
{}
>>> y
{'key': 'vale'}
>>>

C:\>python
Python 2.7.10 (default, May 23 2015, 09:40:3
Type "help", "copyright", "credits" or "lice
>>> x={}
>>> y=x
>>> x['key']='value'
>>> y
{'key': 'value'}
>>> x.clear()
>>> x
{}
>>> y
{}
>>>


2.copy 

 copy 方法但会一个具有相同键值对的新字典(这个方法实现的是浅复制(shallow copy),

因为值本身就是相同的,而不是副本).


x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
print x
y = x.copy()
y['username'] = 'mlh'
y['machines'].remove('bar')
print y
print x


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a6.py
{'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
{'username': 'mlh', 'machines': ['foo', 'baz']}
{'username': 'admin', 'machines': ['foo', 'baz']}

可以看到,当在副本中替换值的时候,原始字典不受影响,但是,如果修改了某个值(原地修改,而不是替换),

原始的字典也会改变,因为同样的值也存储在原字典中





3. fromkeys


fromkeys 方法使用给定的键建立新的字典,每个键默认对应的值为NONE。


print dict.fromkeys(['name','age'])



C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a6.py
{'age': None, 'name': None}


5. hash_key


has_key 方法可以检查字典中是否含有给出的键,表达式d.has_key(k)相当于表达式k in d.

使用哪个方式很大程序上取决于个人的喜好

items = [('name', 'Gumby'), ('age', 42), ('k', 99)]
d=dict(items)
print d

print 'k' in d

print d.has_key('k')


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a4.py
{'k': 99, 'age': 42, 'name': 'Gumby'}
True
True

6.items和iteritems 函数;

d={'title':'Python Web Site','url':'http://www.python.org','spam':0}
print d.items()


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a7.py
[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]

Process finished with exit code 0



d={'title':'Python Web Site','url':'http://www.python.org','spam':0}
print d.iteritems()
print list(d.iteritems())


C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/untitled1/a7.py
<dictionary-itemiterator object at 0x0054FB70>
[('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]