字典方法:
‘’‘key(键),必须唯一,value(值),可以重复’’’
‘’‘字典是无序的’’’
d={3:"three",2:"two",4:"four",1:"one"}
#1、查字典(一定要确定有该键)
print(d[2])
#2、增加
d[5]="a"
print(d)
#3.1删除
# del d
# print(d)
#3.2标准删除
a=d.pop(4) #抛出key值为4的value值
print(d)
print(a)
#3.3随机删除
d.popitem()
print(d)
#4、查找2
print(d.get(5))
print(4 in d) #判断d中是否存在该键值
#5、打印所有的值
print(d.values())
#6、打印所有的键
print(d.keys())
#7、字典拼接
d1={3:"three",2:"two",4:"four",1:"one"}
d2={5:"three",6:"two",7:"four",8:"one"}
d1.update(d2)
print(d1)
#8、打印所有项
d={3:"three",2:"two",4:"four",1:"one"}
print(d.items())
#9、字典初始化
c=dict.fromkeys([2,3,4],"+++")
print(c)
运行结果为:
1: two
2: {3: 'three', 2: 'two', 4: 'four', 1: 'one', 5: 'a'}
3.2: {3: 'three', 2: 'two', 1: 'one', 5: 'a'}
3.2: four
3.3: {3: 'three', 2: 'two', 1: 'one'}
None
4: False
5: dict_values(['three', 'two', 'one'])
6: dict_keys([3, 2, 1])
7: {3: 'three', 2: 'two', 4: 'four', 1: 'one', 5: 'three', 6: 'two', 7: 'four', 8: 'one'}
8: dict_items([(3, 'three'), (2, 'two'), (4, 'four'), (1, 'one')])
9: {2: '+++', 3: '+++', 4: '+++'}
#10'''fromkeys现象说明'''
c=dict.fromkeys([6,7,8],[1,{"a":"A"},"feng"])
print("10:"c)
c[7][1]["a"]="AAA"
print("10:",c)
运行结果为:
10:{6: [1, {'a': 'A'}, 'feng'], 7: [1, {'a': 'A'}, 'feng'], 8: [1, {'a': 'A'}, 'feng']}
10:{6: [1, {'a': 'AAA'}, 'feng'], 7: [1, {'a': 'AAA'}, 'feng'], 8: [1, {'a': 'AAA'}, 'feng']}
#11输出字典中的项
d={3:"three",2:"two",4:"four",1:"one"}
for i in d:
print(d[i]) #输出每一项的Value值
for k,v in d.items():
print(k,v) #输出每一项的key和Value值
运行结果为:
three
two
four
one
3 three
2 two
4 four
1 one
字典案例
llist1={"1.男士夹克":200,"2.加厚外套":250,"3.嘻哈短裤":100,"4.AJ球鞋":1500,"5.短袜":20}
def fun(mon):
def text(*args,**kwargs):
m=int(input("请输入您的工资:"))
for i,k in list1.items():
print(i,k)
mon(*args,**kwargs)
count=0
Sum=0
num={}
global list2
list2=[]
while Sum<=m:
l=input("请输入您选择的商品编号及名称:")
count+=1
for i,k in list1.items():
if i==l:
num=dict.fromkeys([i],k)
list2.append(i)
# print(num)
for i,k in num.items(): #遍历购物车
Sum+=int(k) #将各物品的金额进行求和
if Sum>m:
print("您的金额不足,请及时充值!!")
break
elif Sum<=m:
n=m-Sum
print("购买成功,本次共购买了",count,"件","本次扣除:",Sum,"元","剩余:",n,"元")
return text
def sol():
print("*********欢迎访问购物广场,祝您购物愉快*********")
@fun #方法糖
def lis():
print("*******请选择你所需要的商品编号*******")
def put(list2):
print("您购买的商品如下:")
for i in list2:
print(i)
sol()
lis()
put(list2)
运行结果为:
*********欢迎访问购物广场,祝您购物愉快*********
请输入您的工资:500
1.男士夹克 200
2.加厚外套 250
3.嘻哈短裤 100
4.AJ球鞋 1500
5.短袜 20
*******请选择你所需要的商品编号*******
请输入您选择的商品编号及名称:1.男士夹克
购买成功,本次共购买了 1 件 本次扣除: 200 元 剩余: 300 元
请输入您选择的商品编号及名称:1.男士夹克
购买成功,本次共购买了 2 件 本次扣除: 400 元 剩余: 100 元
请输入您选择的商品编号及名称:3.嘻哈短裤
购买成功,本次共购买了 3 件 本次扣除: 500 元 剩余: 0 元
请输入您选择的商品编号及名称:5.短袜
您的金额不足,请及时充值!!
您购买的商品如下:
1.男士夹克
1.男士夹克
3.嘻哈短裤
这里用到了字典items()方法,利用key值与value值进行商品的选取与个商品价格的计算,判断是否超过你输入的工资数,总价格超过工资数时,输出你能购买的商品列表。其中也用到了装饰器,后续python装饰器专门介绍装饰器内容。