Python学习之dictionary

来源:互联网 发布:经济学是什么 知乎 编辑:程序博客网 时间:2024/06/07 12:50

机器环境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; #更新Ageprint("dict['Age']: \n", dict['Age'])del dict['Name'] #删除键 Namedict.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 = 0for key in prices:  total += prices[key] * stock[key]print ("the total is :\n", total)#购物清单:如果库存>0 则计价,对应库存-1print ("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 totalm = count(shopping_list)print (m)                               

原创粉丝点击