关键词
dic = {'name': 'alex'}
增 dic['age'] = 21 存在就覆盖dic.setdefault()没有就增加删 pop()按照key删除,有返回值cleardel dic['name']popitem()随机删除返回的是元祖改 update查dic.keys()dic.values()dic.items()for k,v in dic.items():dic.get(key, None)案例 元素分类输出产品列表
代码验证
增删改查
dic = {'name': 'larry', 'sex':'nan', 'age':18 }# 增dic['height'] = 185 # 没有键值对,添加dic['name'] = 'xiaozhao' # 有键值对,则值覆盖print(dic)dic.setdefault('weight', 150) # 没有添加dic.setdefault('sex', 'nv') # 有键值对,不做任何改变# 删dic.pop('age') # 按键去删除,有返回值dic.pop('grade', None) # 可设置返回值,不会报错# del dic # 全部删除# print(dic)dic = {'name': 'larry', 'sex':'nan', 'age':18 }dic.popitem() # 随机删除,有返回值为元祖dic.clear() # 清空列表# 改dic = {'name':'xiaozhao', 'age': 18}dic1 = {'name':'xiaoming', 'sex':'male'}dic1.update(dic)print(dic1)# 查for i in dic:print(i)for i in dic.keys():print(i)for i in dic.values():print(i)for k,j in dic.items():print(k, j)
View Code
字典的嵌套
dic = {'name':['xiaoming', 'xiaozhao'],'info':{'time':'1003''first_date':'1005'}'hobby':'book''age': 23}# 增加值dic['name'].append('xiaobao')# xiaozhao大写dic['name'][1] = dic['name'][1].upper()# 修改info.time对应的值dic['info']['time'] = 1003
View Code
元素分类
# 有如下li = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]# 将所有大于66的值保存在字典的第一个key中# 即['k1':大于66的所有值列表,'k2':小于66所有值列表]threshold = 66l_greater = []l_less = []li = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]for i in li:if i > threshold:l_greater.append(i)else:l_less.append(i)dic = {'k1':l_greater, 'k2':l_less}print(dic)
View Code
输出商品列表
# 输出商品列表,用户输入序号,显示用户选中的商品# 商品 li = ['手机', '电脑', '鼠标垫', '游艇']# 要求# 1. 页面显示 序号 + 商品名称 如:# 1 手机# 2 电脑# ...# 2. 用户输入选择的商品序号,然后打印商品名称# 3. 如果用户输入的商品序号有无,则提示输入有误,并重新输入# 4. 用户输入Q或者q,推出程序dic = {'1':'手机','2':'电脑','3':'鼠标垫','4':'游艇'}for i,j in dic.items():print(i, j)count = 1while 1:order = input('请输入商品序号: ').strip()if order.upper() == 'Q': breakif order in ['1','2','3','4']:print(dic[str(order)])breakelse:print('没有找到对应的商品序号,请重新输入')count += 1continue
View Code
购物车
1 ''' 2 网上购物车 3 输入:商品,价格,钱包,购买数量 4 输出:钱够则放至购物车,钱不够则提醒 5 ''' 6 7 li = [{'name':'苹果','price': 10}, 8 {'name':'香蕉','price': 20}, 9 {'name':'橘子','price': 30}] 10 shopping_car = {}11 12 print('welcome to phappiness\'supermarket')13 14 money = input('默想你有多少钱,并输入:')15 if money.isdigit() and int(money) > 0:16while 1:17 for i, k in enumerate(li):18 print('序号{}, 商品{}, 价格{}'.format(i, k['name'], k['price']))19 choice = input('请输入你要购买的商品序号:')20 if choice.isdigit() and int(choice) in range(len(li)):21 num = input('请输入你要购买的数量:')22 if num.isdigit():23 if int(money) >= li[int(choice)]['price'] * int(num):24 money = int(money) - li[int(choice)]['price'] * int(num)25 if li[int(choice)]['name'] in shopping_car:26shopping_car[li[int(choice)]['name']] = shopping_car[li[int(choice)]['name']] + int(num)27 else:28shopping_car[li[int(choice)]['name']] = int(num) 29 print('您的购物车里有{}, 余额为{}'.format(shopping_car, money)) 30 else:31 print('回家问你媳妇要钱去!')32 break33 else:34 print('输入格式错误,请重新输入')
View Code
如果觉得《python入门_老男孩_字典的增删查改》对你有帮助,请点赞、收藏,并留下你的观点哦!