python基础系列三:字典


一、创建字典
字典由键和对应值成对组成。字典也被称作关联数组或哈希表。基本语法如下:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
dict1 = { 'abc': 456 }
dict2 = { 'abc': 123, 98.6: 37 }
注意:
每个键与值用冒号隔开(:),每对用逗号,每对用逗号分割,整体放在花括号中({})。
键必须独一无二,但值则不必。
值可以取任何数据类型,但必须是不可变的,如字符串,数或元组。

#直接创建字典
# coding:utf-8
d={'one':1,'two':2,'three':3}
print d
print d['two']
print d['three']
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
2
3

#利用dict创建字典,输出字典内容
# _*_ coding:utf-8 _*_
items=[('one',1),('two',2),('three',3),('four',4)]
print u'items中的内容:'
print items
print u'利用dict创建字典,输出字典内容:'
d=dict(items)
print d
print u'查询字典中的内容:'
print d['one']
print d['three']
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
items中的内容:
[('one', 1), ('two', 2), ('three', 3), ('four', 4)]
利用dict创建字典,输出字典内容:
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
查询字典中的内容:
1
3

#通过关键字创建字典
# _*_ coding:utf-8 _*_
d=dict(one=1,two=2,three=3)
print u'输出字典内容:'
print d
print u'查询字典中的内容:'
print d['one']
print d['three']

运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
输出字典内容:
{'three': 3, 'two': 2, 'one': 1}
查询字典中的内容:
1
3


二、访问字典里的值
把相应的键放入熟悉的方括弧,如下实例:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Name']: ", dict['Name'];
print "dict['Age']: ", dict['Age'];
#以上实例输出结果:
#dict['Name']: Zara
#dict['Age']: 7

如果用字典里没有的键访问数据,会输出错误如下:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice'];
以上实例输出结果:
#KeyError: 'Alice'[/code]


三、修改字典
向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
#以上实例输出结果:
#dict['Age']: 8
#dict['School']: DPS School


四、删除字典元素
能删单一的元素也能清空字典,清空只需一项操作。
显示删除一个字典用del命令,如下实例:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # 删除键是'Name'的条目
dict.clear(); # 清空词典所有条目
del dict ; # 删除词典
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
#但这会引发一个异常,因为用del后字典不再存在:
dict['Age']:


五、字典键的特性
字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。
两个重要的点需要记住:
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'};
print "dict['Name']: ", dict['Name'];
#以上实例输出结果:
#dict['Name']: Manni
2)键必须不可变,所以可以用数,字符串或元组充当,所以用列表就不行,如下实例:
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name'];
#以上实例输出结果:
#TypeError: list objects are unhashable


--------------------------------------------------
#将文件内容写入字典
fr = open('dic.txt','r')

dic = {}

keys = [] #用来存储读取的顺序

for line in fr:

v = line.strip().split(':')

dic[v[0]] = v[1]

keys.append(v[0])

fr.close()

print(dic)

#写入文件代码 通过keys的顺序写入

fw = open('wdic.txt','w')

for k in keys:

fw.write(k+':'+dic[k]+'\n')

 

fw.close()

---------------------
#字典写入文件
import json

dic = {
'andy':{
'age': 23,
'city': 'beijing',
'skill': 'python'
},
'william': {
'age': 25,
'city': 'shanghai',
'skill': 'js'
}
}

js = json.dumps(dic)
file = open('test.txt', 'w')
file.write(js)
file.close()


六、字典内置函数和方法
Python字典包含了以下内置函数:
cmp(dict1, dict2) #比较两个字典元素。
len(dict) #计算字典元素个数,即键的总数。
str(dict) #输出字典可打印的字符串表示。
type(variable) #返回输入的变量类型,如果变量是字典就返回字典类型。
radiansdict.clear() #删除字典内所有元素
radiansdict.copy() #返回一个字典的浅复制
radiansdict.fromkeys() #创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
radiansdict.get(key, default=None) #返回指定键的值,如果值不在字典中返回default值
radiansdict.has_key(key) #如果键在字典dict里返回true,否则返回false
radiansdict.items() #以列表返回可遍历的(键, 值) 元组数组
radiansdict.keys() #以列表返回一个字典所有的键
radiansdict.setdefault(key, default=None) #和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
radiansdict.update(dict2) #把字典dict2的键/值对更新到dict里
radiansdict.values() #以列表返回字典中的所有值

6.1 clear函数:清除字典中的所有项
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3,'four':4}
print d
d.clear()
print d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
{}
>>> 12345678910

请看下面两个例子
6.1.1
# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
print dd
d={}
print d
print dd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two': 2, 'one': 1}
{}
{'two': 2, 'one': 1}
>>> 123456789101112131415

6.1.2
# _*_ coding:utf-8 _*_
d={}
dd=d
d['one']=1
d['two']=2
print dd
d.clear()
print d
print dd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'two': 2, 'one': 1}
{}
{}
>>> 123456789101112131415

6.1.2与6.1.1唯一不同的是在对字典d的清空处理上,3.1.1将d关联到一个新的空字典上,这种方式对字典dd是没有影响的,所以在字典d被置空后,字典dd里面的值仍旧没有变化。但是在3.1.2中clear方法清空字典d中的内容,clear是一个原地操作的方法,使得d中的内容全部被置空,这样dd所指向的空间也被置空。

6.2 copy函数:返回一个具有相同键值的新字典
# _*_ coding:utf-8 _*_
x={'one':1,'two':2,'three':3,'test':['a','b','c']}
print u'初始X字典:'
print x
print u'X复制到Y:'
y=x.copy()
print u'Y字典:'
print y
y['three']=33
print u'修改Y中的值,观察输出:'
print y
print x
print u'删除Y中的值,观察输出'
y['test'].remove('c')
print y
print x
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
初始X字典:
{'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1}
X复制到Y:
Y字典:
{'test': ['a', 'b', 'c'], 'one': 1, 'three': 3, 'two': 2}
修改Y中的值,观察输出:
{'test': ['a', 'b', 'c'], 'one': 1, 'three': 33, 'two': 2}
{'test': ['a', 'b', 'c'], 'three': 3, 'two': 2, 'one': 1}
删除Y中的值,观察输出
{'test': ['a', 'b'], 'one': 1, 'three': 33, 'two': 2}
{'test': ['a', 'b'], 'three': 3, 'two': 2, 'one': 1}
>>> 123456789101112131415161718192021222324252627282930
注:在复制的副本中对值进行替换后,对原来的字典不产生影响,但是如果修改了副本,原始的字典也会被修改。deepcopy函数使用深复制,复制其包含所有的值,这个方法可以解决由于副本修改而使原始字典也变化的问题。
# _*_ coding:utf-8 _*_
from copy import deepcopy
x={}
x['test']=['a','b','c','d']
y=x.copy()
z=deepcopy(x)
print u'输出:'
print y
print z
print u'修改后输出:'
x['test'].append('e')
print y
print z
运算输出:
输出:
{'test': ['a', 'b', 'c', 'd']}
{'test': ['a', 'b', 'c', 'd']}
修改后输出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'test': ['a', 'b', 'c', 'd', 'e']}
{'test': ['a', 'b', 'c', 'd']}
>>> 12345678910111213141516171819202122

6.3 fromkeys函数:使用给定的键建立新的字典,键默认对应的值为None
# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'])
print d
运算输出:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': None, 'two': None, 'one': None}
>>> 1234567
或者指定默认的对应值
# _*_ coding:utf-8 _*_
d=dict.fromkeys(['one','two','three'],'unknow')
print d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 'unknow', 'two': 'unknow', 'one': 'unknow'}
>>> 1234567

6.4 get函数:访问字典成员
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.get('one')
print d.get('four')
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
1
None
>>> 1234567891011
注:get函数可以访问字典中不存在的键,当该键不存在是返回None

6.5 has_key函数:检查字典中是否含有给出的键
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.has_key('one')
print d.has_key('four')
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
True
False
>>> 1234567891011

6.6 items和iteritems函数:items将所有的字典项以列表方式返回,列表中项来自(键,值),iteritems与items作用相似,但是返回的是一个迭代器对象而不是列表
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
list=d.items()
for key,value in list:
print key,':',value
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
three : 3
two : 2
one : 1
>>> 12345678910111213# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
it=d.iteritems()
for k,v in it:
print "d[%s]="%k,v
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
d[three]= 3
d[two]= 2
d[one]= 1
>>> 12345678910111213

6.7 keys和iterkeys:keys将字典中的键以列表形式返回,iterkeys返回键的迭代器
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print u'keys方法:'
list=d.keys()
print list
print u'\niterkeys方法:'
it=d.iterkeys()
for x in it:
print x
运算结果:
{'three': 3, 'two': 2, 'one': 1}
keys方法:
['three', 'two', 'one']

iterkeys方法:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
three
two
one
>>> 123456789101112131415161718192021

6.8 pop函数:删除字典中对应的键
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
d.pop('one')
print d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
{'three': 3, 'two': 2}
>>> 12345678910

6.9 popitem函数:移出字典中的项
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
d.popitem()
print d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 1}
{'two': 2, 'one': 1}
>>> 12345678910

6.10 setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
print d
print d.setdefault('one',1)
print d.setdefault('four',4)
print d
运算结果:
{'three': 3, 'two': 2, 'one': 1}
1
4
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
>>> 123456789101112

6.11 update函数:用一个字典更新另外一个字典
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3
}
print d
x={'one':1}
d.update(x)
print d
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three': 3, 'two': 2, 'one': 123}
{'three': 3, 'two': 2, 'one': 1}
>>> 123456789101112131415

6.12 values和itervalues函数:values以列表的形式返回字典中的值,itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3,
'test':2
}
print d.values()
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
[2, 3, 2, 123]
>>>

####################################################################################################################################
print('''|---欢迎进入通讯录程序---|
|---1、 查询联系人资料---|
|---2、 插入新的联系人---|
|---3、 删除已有联系人---|
|---4、 退出通讯录程序---|''')
addressBook={}#定义通讯录
while 1:
temp=input('请输入指令代码:')
if not temp.isdigit():
print("输入的指令错误,请按照提示输入")
continue
item=int(temp)#转换为数字
if item==4:
print("|---感谢使用通讯录程序---|")
break
name = input("请输入联系人姓名:")
if item==1:
if name in addressBook:
print(name,':',addressBook[name])
continue
else:
print("该联系人不存在!")
if item==2:
if name in addressBook:
print("您输入的姓名在通讯录中已存在-->>",name,":",addressBook[name])
isEdit=input("是否修改联系人资料(Y/N):")
if isEdit=='Y':
userphone = input("请输入联系人电话:")
addressBook[name]=userphone
print("联系人修改成功")
continue
else:
continue
else:
userphone=input("请输入联系人电话:")
addressBook[name]=userphone
print("联系人加入成功!")
continue

if item==3:
if name in addressBook:
del addressBook[name]
print("删除成功!")
continue
else:
print("联系人不存在")

######################################################################################################################################

 

posted on 2019-01-10 09:43  李松林  阅读(143)  评论(0编辑  收藏  举报

导航