zoukankan      html  css  js  c++  java
  • 字典操作学习小结

    字典操作: 
     字典是一种key-value的数据类型,
     
     字典的特性:
     dict 是无序的
     key必须是唯一的,天生去重
     
     info = {
      'stu1101':"brace";
      'stu1102':"Kitty";
      'stu1103':"Lucy"
     }
     
     print(info)
     print(info['stu1101'])
     
     输出:
     {'stu1101': 'brace', 'stu1102': 'Kitty', 'stu1103': 'Lucy'}
     brace
     
     查找:
     info[stu1101]    #如果key不存在会报错
     info.get("stu1101")   #有则返回,否组不返回
     
     修改:
     info['stu1101']="你好"
     
     增加:
     info['stu1104']="你好"
     
     删除:
     del info['stu1101']
     info.pop('stu1101')
     info.popitem()   #随机删除
     
     
     多级字典嵌套及操作:
     
     省市县:
     
     china_name = {
     "安徽省":{"城市":["合肥"," 安庆","黄山","芜湖","池州"]},
     "上海市":{"城市":["杨浦"," 闵行","浦东","长宁","黄埔"]},
     "江苏省":{"城市":["南京"," 苏州","无锡","常州","苏北"]}
     }
     print(china_name)
     print(china_name["安徽省"])
     print(china_name.keys())
     print(china_name.values())
     输出
     {'安徽省': {'城市': ['合肥', ' 安庆', '黄山', '芜湖', '池州']}, '上海市': {'城市': ['杨浦', ' 闵行', '浦东', '长宁', '黄埔']}, '江苏省': {'城市': ['南京', ' 苏州', '无锡', '常州', '苏北']}}
     {'城市': ['合肥', ' 安庆', '黄山', '芜湖', '池州']}
     dict_keys(['安徽省', '上海市', '江苏省'])
     dict_values([{'城市': ['合肥', ' 安庆', '黄山', '芜湖', '池州']}, {'城市': ['杨浦', ' 闵行', '浦东', '长宁', '黄埔']}, {'城市': ['南京', ' 苏州', '无锡', '常州', '苏北']}])
     
     info = {
     'stu1101': "brace",
     'stu1102': "Kitty",
     'stu1103': "Lucy",
     }
     
     #setdefault 如果key存在,保持当前的,如果不存在,则新增并将默认值赋值。
     info.setdefault("stu1101","xxxxxxxxx")
     print(info)
     info.setdefault("stu1104","xxxxxxxxx")
     print(info)
     
     {'stu1101': 'brace', 'stu1102': 'Kitty', 'stu1103': 'Lucy'}
     {'stu1101': 'brace', 'stu1102': 'Kitty', 'stu1103': 'Lucy', 'stu1104': 'xxxxxxxxx'}
     
     
     update 如果有重复的key增覆盖value,不重复的新增;
     info = {
     'stu1101': "brace",
     'stu1102': "Kitty",
     'stu1103': "Lucy",
     }
     b = {
      "stu1101":"hello",
      "stu1104":"SSSSS",
      "stu1105":"FFFFFF"
     }
     info.update(b)
     print(info)
     print(info.items())   #将字典元素转化为列表元素
     
     
     
     输出:
     {'stu1101': 'hello', 'stu1102': 'Kitty', 'stu1103': 'Lucy', 'stu1104': 'SSSSS', 'stu1105': 'FFFFFF'}
     dict_items([('stu1101', 'hello'), ('stu1102', 'Kitty'), ('stu1103', 'Lucy'), ('stu1104', 'SSSSS'), ('stu1105', 'FFFFFF')])
     
     
     初始化一个字典,key设定为设置项,值为初始化值test
     c = dict.fromkeys([5,6,7],"test")
     print(c)
     
     {5: 'test', 6: 'test', 7: 'test'}
     
     c = dict.fromkeys([5,6,7],[1,{2:"ss"},2])
     print(c)
     c[6][1][2]="Brace"
     print(c)
     输出:
     {5: [1, {2: 'ss'}, 2], 6: [1, {2: 'ss'}, 2], 7: [1, {2: 'ss'}, 2]}
     {5: [1, {2: 'Brace'}, 2], 6: [1, {2: 'Brace'}, 2], 7: [1, {2: 'Brace'}, 2]}
     
     for i in c:     #高效,直接循环;
      print(i,c[i])
      
     输出:
     5 [1, {2: 'Brace'}, 2]
     6 [1, {2: 'Brace'}, 2]
     7 [1, {2: 'Brace'}, 2]
     
     for k,v in c.items():  #由把字典转列表的过程,数据量大,效率低。
        print(k,v)
     
     5 [1, {2: 'Brace'}, 2]
     6 [1, {2: 'Brace'}, 2]
     7 [1, {2: 'Brace'}, 2]
     
     
    作业:
     用户入口:
     1. 商品信息存在文件里
     2. 已够商品,余额记录
     
     商家入口
     2. 可以添加商品,修改商品价格
     
     
    作业:
     启动程序后,让用户输入工资,然后打印商品列表
     运行用户根据商品编号购买商品
     用户选择商品后,检查余额是否够,够直接扣款,不够就提醒
     可随时退出,退出时,打印已购买商品和余额
     
     
    # Author:Brace Li
    import sys
    while True:
        salary = input("pls input your salary:")
        if salary.isdigit():
            salary = int(salary)
            break
    products_list = [
        ("Iphone",5800),
        ("Mac Pro",9800),
        ("Bike",800),
        ("Watch",10600),
        ("Book",45)
    ]
    product_box = []
    while True:
        product_id = []
        for i,v in enumerate(products_list):
            print(i, v)
            product_id.append(i)
        while True:
            pro_num = input("select product:")
            if not pro_num.isdigit():
                print("Error: >> Product number error!")
                continue
            product_num = int(pro_num)
            if product_num in product_id:
                break
            else:
                print("Error: >> Product number error!")
                continue
        product_box.append(products_list[product_num])
        print("the product '%s' had been selected successfully" %products_list[product_num][0])
        print()
        print("*" * 80)
        print("1. Exit System, 2.Continue, 3.Charge")
        print("*" * 80)
        while True:
            customer_action = input("select>>")
            if not customer_action.isdigit():
                print("Error: Input error!")
                continue
            customer_action = int(customer_action)
            if not customer_action in (1,2,3):
                print("Error: Input error!")
                continue
            if customer_action == 1:
                sys.exit()
            elif customer_action == 2:
                break
            else:
                print(product_box)
                total_charge = 0
                print("*" * 40)
                for n in list(set(product_box)):
                    print("|| %s || %d ||" %(n[0],product_box.count(n)))
                    print("*" * 40)
                    total_charge += n[1]*product_box.count(n)
                print("Product total price: %d" %total_charge)
                print("*" * 40)
                if salary > total_charge:
                    balance = salary - total_charge
                    print("Charging Successfully !!!!!")
                else:
                    balance = salary
                    print("Charging fail, salary not enough !!!!!")
                print("balance: %d" % balance)
                sys.exit() 
  • 相关阅读:
    bch算法生成nand flash中512byte校验和
    CFileDialog用法总结
    c++修改打印机名称
    c++连接打印机(转载)
    转发:for /f命令之—Delims和Tokens用法&总结
    c++中DLL文件的编写与实现——三步走
    GhostScript说明
    打印机API
    c++中DLL文件的编写与实现——三步走(2)
    windows程序设计基础知识
  • 原文地址:https://www.cnblogs.com/brace2011/p/9180477.html
Copyright © 2011-2022 走看看