python之dictionary
1、python3字典
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中
dict1 = {key1:value1,key2:value2}
字典的键必须是唯一的 ,但值则不必;值可以去任何数据类型,但键必须是不可变的,如字符串,数字或元组。
>>> dict1 = {'name':'python','age':'20','character':'scripts'}
2、访问字典
使用key访问对应的值,如果key不存在则报错
>>> dict1 = {'name':'python','age':'20','character':'scripts'} >>> print(dict1['name']) python >>> print(dict1['age']) 20
>>> print(dict1['age1'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'age1
3、修改、删除字典元素
将指定的key赋值即可修改字典元素值,能删除单个的元素也能清空字典
>>> dict2 = {'key1':123,'key2':'dictionary'} >>> dict2['key1']=888 #修改对应的key的值 >>> print(dict2) {'key2': 'dictionary', 'key1': 888} >>> dict2['key3']='python3' #给字典添加元素 >>> print(dict2) {'key2': 'dictionary', 'key1': 888, 'key3': 'python3'} >>> del dict2['key1'] #删除键 >>> print(dict2) {'key2': 'dictionary', 'key3': 'python3'} >>> dict2.clear() #清空字典内容 >>> dict2 {} >>> del dict2 #删除字典 >>> dict2 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'dict2' is not defined #字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。 #不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住 >>> dict = {1:'a',2:'b',1:'c'} >>> print(dict) {1: 'c', 2: 'b'} #键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行 >>> dict = {1:'a','abc':'python',('tuple','values'):'abc',['list1']:'listname'} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'
4、字典内置函数
>>> dict1 = {1:'a',2:'b',3:'c',4:'d'} >>> len(dict1) #计算字段元素个数 4 >>> str(dict1) #输出字典,以可以打印的字符串表示 "{1: 'a', 2: 'b', 3: 'c', 4: 'd'}" >>> type(dict1) #返回变量类型 <class 'dict'>
5、python3字典方法
>>> dict = {'a':1,'b':2} >>> dict.clear() #清除字典内的所有元素 >>> dict {} >>> dict = {'a':1,'b':{'c':22,'d':33}} >>> dict1 = dict.copy() #返回字典的浅复制,即只拷贝第一层键对应值 >>> dict1 {'b': {'d': 33, 'c': 22}, 'a': 1} >>> dict1.fromkeys(range(5),'000') #创建一个新字典,迭代序列做字典的键,value为字典的初始值,此处为"000" {0: '000', 1: '000', 2: '000', 3: '000', 4: '000'} >>> dict1 = {'k1':'v1','k2':'v2'} >>> print(dict1.get('k3')) #get查找key是否存在,如果不存在则用None,或指定值 None >>> print(dict1.get('k3','python')) python >>> 'k1' in dict1 #判断键是否存在,存在返回true,否则返回false True >>> 'k3' in dict1 False >>> dic = {'k1':'v1','k2':'v2'} >>> print(dic.items()) #以列表返回可遍历的(键, 值) 元组数组 dict_items([('k1', 'v1'), ('k2', 'v2')])
>>> for k,v in dic.items(): #迭代循环取值 ... print(k,v) ... k1 v1 k2 v2
>>> print(dic.keys()) #以列表返回字典的所有键 dict_keys(['k1', 'k2']) >>> print(dic.values()) #以列表返回字典的所有值 dict_values(['v1', 'v2']) >>> dic.setdefault('k3','v3') #和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default或指定 'v3' >>> dic {'k1': 'v1', 'k3': 'v3', 'k2': 'v2'} >>> dic1 = {1:22,2:33,3:44} >>> dic.update(dic1) #把字典dic1的键/值对更新到dic里 >>> dic {1: 22, 2: 33, 3: 44, 'k3': 'v3', 'k1': 'v1', 'k2': 'v2'} >>> dic.pop(1) #删除字典给定的键值,返回值为删除的值,key必须指定,如删除键不存在则返回default值,可指定。 22 >>> dic {2: 33, 3: 44, 'k3': 'v3', 'k1': 'v1', 'k2': 'v2'} >>> dic.pop(1,'hehe') 'hehe' >>> dic.popitem() #随机删除字典中的一对键和值(一般删除最前的对) (2, 33) >>> dic.popitem() (3, 44)
6、小实例
根据奇数和偶数生成字典元素 dct1 = {} for i in range(20): if i%2 == 1: if 'odd' in dct1.keys(): dct1['odd'].append(i) else: dct1['odd'] = [i,] else: if 'even' in dct1.keys(): dct1['even'].append(i) else: dct1['even'] = [i,] print(dct1) 输出结果: {'odd': [1, 3, 5, 7, 9, 11, 13, 15, 17, 19], 'even': [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]}
登陆购物车:
1 #!/usr/bin/env python 2 #coding:utf8 3 #file:Administrator 4 #time:20170926 5 import sys,os 6 #统计三次用户错误锁定 7 count = 0 8 #用户密码字典 9 name_pass = {'user1':'123','user2':'456','user3':'789'} 10 for i in range(10): 11 name_input = input('请输入用户名:') 12 if name_input in name_pass.keys(): #判断用户存在否 13 passwd_input = input('请输入密码:') 14 if passwd_input == name_pass[name_input]: #判断对应用户密码 15 print('恭喜登陆成功!') 16 break 17 else: 18 if count > 1: 19 print('3次输入错误,您账号已锁定') 20 exit() 21 print('{}用户名不存在或密码错误,请重新输入!'.format(name_input)) 22 count += 1 23 else: 24 print('{}用户不存在'.format(name_input)) 25 continue 26 #商品列表 27 shop_list = [ 28 ['iphone7',6500], 29 ['iphone6',4500], 30 ['金立s10',3400], 31 ['华为r79',2888], 32 ['魅族NOTE5',1888], 33 ['opppR9',3600], 34 ] 35 money = eval(input('请输入你的预购金额:')) 36 shop_out = [] #购物车 37 all_kaixiao = 0 #统计值 38 while True: 39 print('++++++++++商品清单++++++++++++++') 40 for num,i in enumerate(shop_list,1): 41 if isinstance(i,list): 42 shop_li = i[0]+"\t"+str(i[1]) 43 print(num,shop_li) 44 else: 45 print(i) 46 print('q:退出\np:打印清单') 47 shop_name = input('请输入要购买的商品编号:') 48 shop_name = str(shop_name) 49 50 if shop_name == 'q': 51 exit() 52 elif shop_name == 'p': #打印购物明细 53 print('------购物明细------') 54 for number,i in enumerate(shop_out,1): 55 if isinstance(i,list): 56 hehe = i[0]+":"+str(i[1]) 57 print(number,hehe) 58 else: 59 print(number,i) 60 print('---总计金额:%s---'%(all_kaixiao)) 61 continue #跳出循环,不然会输出非法信息 62 if shop_name.isdigit() == 1: #判断是否为数字 63 shop_name = int(shop_name) 64 else: 65 print('您的输入非法,请重新输入') 66 continue 67 unm1 = int(len(shop_list)) 68 if shop_name not in range(1,unm1+1): #判断输入商品编号是否在序列中 69 print('输入有误,请重新输入!') 70 continue 71 else: 72 price = int(shop_list[shop_name - 1][1]) #商品单价 73 if money < price: 74 print('您的金额不足,无法购买') 75 continue 76 money = money - price # 剩余金额 77 out = shop_list[shop_name - 1][:] # 购买商品信息 78 shop_out.append(out[:]) # 加入购物车 79 all_kaixiao +=price #汇总消费 80 print('您购买的商品是:{}单价:{}元'.format(*out)) 81 print('您还可以消费:{}'.format(money))