1.创建和访问字典
key key对应的值
dict={key1:值1,key2:值2,……….}
brand=["李宁","naike",'adidas']
slogan=['一切皆有可能','just','nothing is impossible']
变成字典:
dict1={'李宁':'一切皆有可能','naike':'just do it','adidas':'nothing is impossible'}
print('李宁的口号是:',dict1['李宁'])
结果为:
#李宁的口号是: 一切皆有可能
或者
利用dict关键字
dict1=dict(((1,'one'),(2,'two'),(3,'three'),(4,'four')))
dict1结果:
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
或者:
dict2=dict(李宁='一切皆有可能',Nike='just do it')
结果:
#{'Nike': 'just do it', '李宁': '一切皆有可能'}
注:
关键字创建字典顺序会通过排序 发生一定变化
2.替换和添加
若字典中存在该key则修改key值:
dict2['李宁']='啥都不可能'
结果为:
{'Nike': 'just do it', '李宁': '啥都不可能'}
若字典中不存在则添加该key和key值:
dict2['爱迪生']='天才'
{'爱迪生': '天才', 'Nike': 'just do it', '李宁': '啥都不可能'}
3.字典的内建方法
fromkeys(key,key值)
创建并返回一个新的字典
dict2.fromkeys('1','one')
结果为:
{‘1’,'one'}
keys
返回字典键的列表:
values
返回左右的键值
items
返回一个包含字典中的键,值对元组的列表
dict2=dict2.fromkeys(range(32),'赞')
返回:
{0: '赞', 1: '赞', 2: '赞', 3: '赞', 4: '赞', 5: '赞', 6: '赞', 7: '赞', 8: '赞', 9: '赞', 10: '赞', 11: '赞', 12: '赞', 13: '赞', 14: '赞', 15: '赞', 16: '赞', 17: '赞', 18: '赞', 19: '赞', 20: '赞', 21: '赞', 22: '赞', 23: '赞', 24: '赞', 25: '赞', 26: '赞', 27: '赞', 28: '赞', 29: '赞', 30: '赞', 31: '赞'}
keys用法:
for eachkey in dict1.keys():
print(eachkey)
返回:
0,1,2,3,4....31
values用法:
for eachvalue in dict2.values():
print(eachvalue)
返回:
赞,赞,赞.....
item用法:
for eachitem in dict2.items():
print(eachitem)
返回:
(0, '赞')
(1, '赞')
(2, '赞')
(3, '赞')
(4, '赞')
(5, '赞')
(6, '赞')
......
注:如果索引没有的值会报错
例如:
print(dict2[32])会报错
print(dict2.get(32))返回None
print(dict2.get(32,‘木有’))返回‘木有’(没有32这个索引,只到31)
print(dict2.get(30,‘木有’))返回‘赞’
in 与 not in 也可以用于字典中
clear():
清空字典
dict2.clear()
dict2返回:
{}
copy方法
浅拷贝方法,对对象表层的拷贝
a={1:'one',2:'two'}
a
{1: 'one', 2: 'two'}
b=a.copy()
b
{1: 'one', 2: 'two'}
c=a
c
{1: 'one', 2: 'two'}
id(a)#原值
71118600
id(b)#浅拷贝
71110792
id(c)#赋值
71118600
#因此发现浅拷贝和赋值的不同,他们的id相同
c[4]='four'
c
{1: 'one', 2: 'two', 4: 'four'}#赋值
a
{1: 'one', 2: 'two', 4: 'four'}
b
{1: 'one', 2: 'two'}#浅拷贝
#如重新赋值,浅拷贝不发生改变
pop(key)函数
给一个键,返回键对应的值
c.pop(1)
返回‘one’
popitem()
随机从字典中弹出一个数据(也就是删除该数据的意思)
a.popitem()
(1, 'one')
a.popitem()
(2, 'two')
a.popitem()
(3, 'three')
a.popitem()
(4, 'four')
a.popitem()#此时a中的数据都已经弹出删除,所以a已经为空了,没法使用popitem
setdefault()
为字典加入一个值,并赋值为默认值
a.setdefault(‘小白’)
a返回:
{‘小白’:None}
习题及答案
1. 尝试将一下数据(‘F’:70,’C’:67,’h’:104,’i’:105,’s’:115)创建为一个字典并访问键‘C’对应的值?
创建
dict1={'F':70,'c':67,'h':104,'i':105,'s':115}
或者利用dict关键字
dict1=dict((('s',115),('i',105),('c',67)))
或者
dict1=dict(s=115,i=105,c=67)
访问:
dict1['C']
返回:
67
2.用方括号(“[]”)括起来的数据我们叫列表,那么使用大括号(“{}”)括起来的数据我们就叫字典对吗?
不对
a={1,2,3,4,6}
type(a)
<class 'set'>
不难发现,我们用大括号“{}”把一些数据括起来了,但是由于没有反应出这些数据有映射关系,所以创建出来的不是字典,而是叫‘set’的东西
3.你是如何理解有些东西字典做得到,但是万能的列表却难以实现了呢?
比如李宁 口号为一切皆有可能,需要用利用去访问口号,这种情况下列表难以做到,就是两个有关联的东西用字典做起来比较方便一些,
4.下边这些代码,他们都在执行一样的操作,你能看出区别么?
a=dict(one=1,two=2,three=3)
b={'one':1,'two':2,'three':3}
c=dict(zip(['one','two','three'],[1,2,3]))
d=dict([('two',2),('one',1),('three',3)])
e=dict({'three':3,'one':1,'two':2})
都可以用来创建字典,没什么区别
5.尝试用字典的特性编写一个通讯录程序
print('欢迎进入通讯录程序')
print('1.查询联系人')
print('2.插入联系人')
print('3.删除联系人')
print('4.退出通讯录')
contact={'小王':123,'小李':254,'小张':125,'小徐':785}
while 1:
temp=int(input("请输入你的选择:"))
if temp==1:
name=input("请输入要查询的姓名:")
if name in contact.keys():
print(contact[name])
else:
print("该联系人不在通讯录中")
if temp==2:
name=input("请输入要添加的联系人姓名:")
number=input("请输入联系人电话:")
contact[name]=number
if temp==3:
name=input("请输入要删除的联系人姓名:")
if name in contact.keys():
contact.pop(name)
else:
print("该联系人不在通讯录中")
if temp==4:
break
第26讲:字典习题答案
0.python的字典是否支持一键多值?
不支持,对相同的键再次赋值直接覆盖
1.在字典中,如果视图为一个不存在的键赋值会怎么样?
会自动创建该键并添加相应的值进去
2.成员操作符in或者not in可以检查一个元素是否存在一个序列中,当然也可以用来检查一个键是否存在字典中,那么请问哪种的检查效率更高一些?为什么
字典更高效一些,因为字典的原理是使用哈希算法存储,一步到位,不需要使用其他算法进行匹配,因此效率比较高
3.python对键和值有没有数据类型的限制?
python对键的要求相对严格一点,要求他们必须是可哈希的对象
4.目测下面代码。字典1的内容是什么
dict1.fromkeys((1,2,3),(‘one’,‘two’),‘three’)
返回:
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
5.如果你需要将字典dict1={1:’one’,2:’two’,3:’three’}拷贝到dict2,你应该怎么做?
#copy浅拷贝方法
dict2=dict1.copy()
#直接赋值
dict2=dict1
6.尝试编写一个用户登录程序(尝试将功能封装成函数)
user_data={'小王':123,'小李':254,'小张':125,'小徐':785}
def new_user():
prompt='请输入用户名:'
while 1:
name=input(prompt)
if name in user_data:
prompt='此用户已经被占用,请重新输入'
continue
else:
break
password=input("请输入密码:")
user_data[name]=password
print("注册成功,赶快登陆吧")
def old_user():
prompt='请输入用户名:'
while 1:
name=input(prompt)
if name not in user_data:
prompt='您输入的用户名不存在,请输入:'
continue
else:
break
password=input("请输入密码:")
pwd=user_data.get(name)
if password==pwd:
print("欢迎进入系统!")
else:
print("密码错误")
def showmenu():
prompt='''
新建用户:N/n
登录账号:E/e
退出程序:Q/q
请输入指令代码:'''
while 1:
chosen=False
while not chosen:
choice=input(prompt)
if choice not in 'EQNneq':
print('代码指令错误,请重新输入')
else:
chosen=True
if choice=='q'or choice=='Q':
break
if choice=='N'or choice=='n':
new_user()
if choice=='e'or choice=='E':
old_user()
showmenu()