python第26课练习——字典(2)
2019-05-27 本文已影响0人
YoYoYoo
1、Python的字典是否支持一键(Key)多值(Value)?
答:不支持,对相同的键再次赋值会将上一次的值直接覆盖。
>>> dict1 = {1:'one',1:'yi'}
>>> dict1[1]
'yi'
2、在字典中,如果试图为一个不存在的键(Key)赋值会怎样?
答:会自动创建对应的键(Key)并添加相应的值(Value)进去。
3、成员资格操作符(in 和 not in)可以检查一个元素是否存在序列中,当然也可以用来检测一个键(Key)是否存在于字典中,那么请问哪种检查效率更高?为什么?
答:在字典种检查键 (Key)是否存在比在序列种检查指定元素是否存在更高效。因为字典的原理是使用哈希算法存储,一步到位,不需要使用查找算法进行匹配,效率非常高。
4、Python对键(Key)和值(Value)有没有类型的限制?
答:
- Python对键(Key)的要求要严格一些,要求他们必须是可哈希(Hash)的对象,不能是可变类型(包括变量、列表、字典本身等)。
- 但是对值是没有任何限制的,他们可以是任意的Python对象。
5、请目测下边代码执行后,字典dict1的内容是什么?
>>> dict1.fromkeys((1,2,3),('one','two','three'))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
>>> dict1.fromkeys((1,3),'数字')
{1: '数字', 3: '数字'}
6、如果你需要将字典dict1 = {1:'one',2:'two',3:'three'}拷贝到dict2,你应该怎么做?
答:可以用字典的copy()方法:dict2 = dict1.copy(),在其他语言转移到Python的小伙伴刚开始会习惯性直接用赋值的方法(dict2 = dict1),这样子做在Python种只是将对象的引用拷贝过去而已。
看以下区别:
>>> a = {1:'one',2:'two',3:'three'}
>>> b = a.copy()
>>> c = a
>>> c[4] = 'four'
>>> c
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> a
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> b
{1: 'one', 2: 'two', 3: 'three'}
7、尝试编写一个用户登录程序(这次尝试将功能封装成函数)实现以下功能。
image.png
参考代码:
user_data = {}
def new_user():
prompt = '请输入用户名:'
while True:
name = input(prompt)
if name in user_data:
prompt = '此用户名已经被使用,请重新输入:'
continue
else:
break
passwd = input('请输入密码:')
user_data[name] = passwd
print('注册成功,赶紧试试登陆吧!')
def old_user():
prompt = '请输入用户名:'
while True:
name = input(prompt)
if name not in user_data:
prompt = '您输入的用户名不存在,请重新输入:'
continue
else:
break
passwd = input('请输入密码:')
pwd = user_data.get(name)
if passwd == pwd:
print('欢迎进行XXX系统,请点击右上角的X结束程序!')
else:
print('密码错误!')
def showmenu():
prompt = '''
|--- 新建用户:N/n ---|
|--- 登陆账号:E/e ---|
|--- 退出程序:Q/q ---|
|--- 请输入指令代码:'''
while True:
chosen = False
while not chosen:
choice = input(prompt)
if choice not in 'NnEeQq':
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()