python核心编程v2.0 第7章习题(上)

本文介绍了Python字典的update()方法,强调了键必须可哈希且不可变的特点,并通过示例讲解了相关操作。此外,还涉及到使用Tkinter创建简单登录注册程序,用户信息存储在字典中。
摘要由CSDN通过智能技术生成

若答案有误,欢迎评论留言。
1.update()方法可以将一个字典的内容添加到另外一个字典中。重复的键的值被覆盖,不存在的键被添加。

2.字典的键必须是可哈希的。解释器调用哈希函数,根据字典中键的值来计算存储你的数据的位置。为了可靠地存储或获取相关的数据,键不可变。所有的不可变类型均可作为键。元组中只包括字符串或数字等不变参数才能作为有效的键。

3.
a)

dic = {
  'a':'today','c':'we','b':'try'}

for eachkey in sorted(dic):
    print eachkey

b)

dic = {
  'a':'today','c':'we','b':'try'}

for eachkey in sorted(dic):
    print eachkey,
    print dic[eachkey]

c)

dic = {
  'a':'today','c':'we','b':'try'}

#lambada隐函数,value在这里表示列表的一个元素,即一个元组。
for i, j in sorted(dic.items(), key=lambda value: value[1]):
    print "%s:%s" % (i, j)

4.

lis = [1,2,3,4]
lis_value = ['a','b','c','d']

print dict(zip(lis,lis_value))

5
a)

import time
db = {}

def newuser():
    prompt = 'login desired:'
    while True:
        name = raw_input(prompt)
        if db.has_key(name):
            prompt = 'name taken,try another'
            continue
        else:
            break
    pwd = raw_input('passwd:')
    #存下新用户第一次登录时间
    db[name] = [pwd,time.strftime("%Y %m %d %H %M", time.localtime())]

def olduser():
    name = raw_input('login:')
    pwd = raw_input('passwd:')
    passwd = db[name][0]
    if passwd == pwd:
        print 'welcome back',name
        #记录登录时间
        ti = time.strftime("%Y %m %d %H %M", time.localtime())
        lis1 = ti.split(' ')
        lis2 = db[name][1].split(' ')
        # print lis1
        # print lis2
        #与db中记录的登录时间作对比
        if lis1[0] == lis2[0]:
            if lis1[1] == lis2[1]:
                if lis1[2] == lis2[2]:
                    if int(lis1[3])-4<int(lis2[3]):
                        print 'you alraedy logged in at %s' %db[name][1]
        #更新登录时间
        db[name][1] = ti
    else:
        print 'login incorrect'

def showmenu():
    prompt = '''
    N
    E
    Q
    enter choice:
    '''

    done = False
    while not done:
        chosen = False
        while not chosen:
            try :
                choice = raw_input(prompt).strip()[0]
            except(EOFError,KeyboardInterrupt):
                choice = 'Q'
            print 'you picked :[%s]' % choice
            if choice not in 'NEQ':
                print 'invaild option'
            else:
                chosen = True

        if choice == 'Q':done = True
        if choice == 'N':newuser()
        if choice == 'E':olduser()

if __name__ == '__main__':
    showmenu()

b)

def delete():
    name = raw_input('you want to delete')
    del db[name]
    print '%s has been dele
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值