Python学习之dictionary

机器环境Ubuntu16.04, vim ,python3

  • python3字典基本介绍

    字典是另一种可变容器模型,且可存储任意类型对象。

    字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

    d = {key1 : value1, key2 : value2 }
  • 创建:键必须是唯一的,值可以不唯一

    dict = {'A': '41', 'B': '42', 'C': '43'}
  • 修改:增加新的新的键/值对,修改或删除已有键

    
    #!/usr/bin/python3                                                              
    
    
    # -*- coding: utf-8 -*-
    
    """
    
    # Author: EricRay
    
    
    # Created Time : 2017-11-02 09:00:58
    
    
    
    # File Name: dic.py
    
    
    # Description:
    
    
    """
    
    dict = {'Name':'Eric', 'Age': '18', 'Class': 'F'}
    
    print("dict['Name']: ", dict['Name'])
    print("dict['Age']: ", dict['Age'])
    
    dict['Age'] = 8; #更新Age
    print("dict['Age']: \n", dict['Age'])
    del dict['Name'] #删除键 Name
    dict.clear()  #删除字典
    del dict # 删除字典
    
    """
    应为字典不再存在,所以下面print会报异常
    print("dict['Name']: ", dict['Name'])
    print("dict['Age']: ", dict['Age'])                    
    """
  • 特性

    字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。

    1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住。

    2)键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行

  • 代码

    
    #!/usr/bin/python3                   
    
    
    # -*- coding: utf-8 -*-
    
    """
    
    # Author: EricRay
    
    
    # Created Time : 2017-11-02 09:00:58
    
    
    
    # File Name: dic.py
    
    
    # Description:模拟超市购物
    
    
    """
    
    
    #库存和单价
    
    prices = { 
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
    }
    stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
    }
    
    
    #输出水果和其对应的单价
    
    print ("the detail is: \n")
    for key in prices:
      print (key)
      print ("price: %s" %prices[key])
      print ("stock: %s\n" %stock[key])
    
    
    #计算库存总价
    
    total = 0
    for key in prices:
      total += prices[key] * stock[key]
    print ("the total is :\n", total)
    
    
    #购物清单:如果库存>0 则计价,对应库存-1
    
    print ("your shopping list:\n")
    
    shopping_list = ["banana", "orange", "apple"]
    
    def count(fruits):
      total = 0
      for fruit in fruits:
          if stock[fruit] > 0:
              total = total + prices[fruit]
              stock[fruit] -= 1
      return total
    
    m = count(shopping_list)
    print (m)                               

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值