python核心编程 第七章 字典


#字典:哈希值(键)+对象(值)1:n
#哈希值可以用字符串做键,与存储数据相关联,无序。
'--------------------------------'
#创建字典,赋值

dict1 = {}
dict2 = {'name':'earth','port':'80'}
print dict1,dict2

#dict()
fdict = dict((['x',1],['y',2]))
print fdict

#{}.fromkeys
ddict = {}.fromkeys(('x','y'),-1)
#默认值都为-1
edict = {}.fromkeys(('foo','bar'))
#默认值均为none
print ddict,edict

'-------------------------------'
#访问字典的值

#keys()
for key in dict2.keys():
    print key,dict2[key]
    #键,值

#迭代器
for key in dict2:
    print key,dict2[key]

dict2['name']
#获得name的值

'------------------------------------'
#检查字典中是否有某一个键

'server' in dict2    #false
'name' in dict2        #ture

'--------------------------------'
#逐一添加,键混用数字和字符串

dict3 = {}
dict3[1] = 'abc'
dict3['1'] = 3
print dict3

#更新字典
dict3[1] = 'xyz'
#删除,不常见 del
del dict3['1']
print dict3

#''''''''''''''''''''''''''映射类型操作符''''''''''''''''''''
'------------------------------------------------'
#字典不支持拼接和重复

#字典比较,不是很有用,不常见

print dict1 < dict2
cmp(dict2,dict1)

#1 先比元素个数,再比键,再比值

#''''''''''''''''''''''''映射类型的内建函数和工厂函数’‘’‘’‘
print type(dict2)
#print str(dict3)

'-----------------------------'
#dict()新建

dict4 = dict(zip(('x','y'),(1,2)))
dict5 = dict([['x',1],['y',2]])
dict8 = dict(x=1,y=2)
print dict4,dict5,dict8

#len()
print len(dict4)
#hash()返回键对应的值
print hash(dict4['x'])

#’‘’‘’‘’‘’‘’‘’‘’‘’映射类型的内建方法‘’‘’‘’‘’‘’‘’‘’
#keys()返回列表:字典所有键,for循环来获取字典的值
#values() 字典所有值
#items() 键+值

#keys()返回列表:字典所有键,for循环来获取字典的值
#values() 字典所有值
#items() 键+值 
print dict4.keys()
print dict4.values()
print dict4.items()

#复制
dict6 = dict4.copy()

#得到有序可遍历
for key in sorted(dict2):
    print key,dict2[key]

#get()查找,  找不到不会异常
print dict4.get('home') #none
print dict4

print dict4.get('home','http') #http
print dict4

'------------------字典的键------------'
#不允许一键 多值,取最近的赋值

dict1 = {'foo':789,'foo':123}
print dict1
dict1['foo'] = 2    #重新赋值后只保存一个
print dict1

#键必须是可哈希的,列表和字典可变类型不能作为键
#元组不可变,但是元组里面全是数字或字符串这样的不可变参数才可以作为

-------------------------------------------------------------------------------

#encoding=utf-8
# 示例 7.1 字典示例(userpw.py)
# 这个程序管理用于登录系统的用户信息:登录名字和密码。登录用户帐号建立后,已存在用户
# 可以用登录名字和密码重返系统。新用户不能用别人的登录名建立用户帐号。

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] = passwd#链表的键与值

def olduser():
    name = raw_input('login: ')
    pwd = raw_input('passwd: ')
    passwd = db.get(name)
    if passwd == pwd:
        print 'welcome back', name
    else:
        print 'login incorrect'

def showmenu():
    prompt = """
    (N)ew User Login
    (E)xisting User Login
    (Q)uit
    Enter choice: """

    done = False
    while not done:
        chosen = False
        while not chosen:
            try:
                choice = raw_input(prompt).strip()[0].lower()
            except (EOFError, KeyboardInterrupt):
                choice = 'q'
                print '
You picked: [%s]' % choice
                if choice not in 'neq':
                    print 'invalid option, try again'
                else:
                    chosen = True
                    done = True 

newuser()
olduser()

if __name__ == '__main__':
    showmenu()
原文地址:https://www.cnblogs.com/lovely7/p/5741791.html