若答案有误,欢迎评论留言。
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