字典常用方法

对于可以改变对象的值的可变对象的方法是没有返回值的
sorted(seq): 不会改变原有列表,字典

 方法      描述
dict.clear() 删除字典中所有元素
dict.copy() 返回字典(浅复制)的一个副本
dict.fromkeys(seq, val = None) 创建并返回一个新字典,以 seq 中的元素做该字典的键,val 做该字典中所有键对应的初始值(如果不提供此值,则默认为 None)
dict.get(key, default = None) 对字典 dict 中的键 key,返回它对应的值 value, 如果字典中不存在此键,则返回 default 的值(参数 default 的默认值为 None)
dict.has_key(key) 如果键(key)在字典中存在,返回 True,否则返回 False. 可以使用 in 和 not in 替代
dict.items() 返回一个包含字典中(键,值)对元组的列表
dict.keys() 返回一个包含字典中键的列表
dict.iter() 返回一个迭代子,而不是一个列表
dict.pop(key[, default]) 如果字典中 key 键存在,删除并返回 dict[key], 如果 key 键不存在,且没有给出 default 的值,引发 KeyError 异常
dict.setdefault(key, default = None) 如果字典中不存在 key 键,由 dict[key] = default 为它赋值
dict.update(dict2) 将字典 dict2 的键-值对添加到字典 dict
dict.values() 返回一个包含字典中所有值的列表
 1 #模拟用户名密码
 2 db = {}
 3 
 4 def newuser():
 5     promput = 'login desired: '
 6     while True:
 7         name = raw_input(promput)
 8 
 9         if name in db:
10             promput = 'name taken, try another: '
11             continue
12         else:
13             break
14 
15     pwd = raw_input('password')
16     db[name] = pwd
17 
18 def olduser():
19     name = raw_input('login: ').strip()
20     pwd = raw_input('password: ')
21     password = db.get(name)
22 
23     if password == pwd:
24         print 'welcome back', name
25     else:
26         print 'login incorrect'
27 
28 def showmenu():
29     prompt = """
30         (N)ew User Login
31         (E)xisting User Login
32         (Q)uit
33 
34         Enter choice:
35         """
36 
37     done = False
38     while not done:
39         chosen = False
40         while not chosen:
41             try:
42                 choice = raw_input(prompt).strip()[0].lower()
43             except (EOFError, KeyboardInterrupt):
44                 choice = 'q'
45 
46             print '\n You picked: [%s]' % choice
47 
48             if choice not in 'neq':
49                 print 'invalid option, try again'
50             else:
51                 chosen = True
52 
53         if choice == 'q':done = True
54         if choice == 'n':newuser()
55         if choice == 'e':olduser()
56 
57 
58 if __name__ == '__main__':
59     showmenu()
原文地址:https://www.cnblogs.com/Roger1227/p/3074016.html