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)
阅读全文
1 0
- Python学习之dictionary
- python学习笔记--Dictionary
- 深入学习Python内置数据类型之——字典(Dictionary)
- 深入学习Python内置数据类型之——字典(Dictionary)
- python入门学习教程之dictionary(字典)
- gensim学习之Dictionary
- python学习------dictionary和set
- Python 入门之 字典 Dictionary
- gensim学习之corpora.Dictionary
- python学习(1)-字典 (Dictionary)
- python学习笔记16:tuple, set, dictionary
- Python学习练习3----Dictionary(字典)
- 王亟亟的Python学习之路(五)-dictionary,set,函数,函数参数
- Python学习整理之 列表list 元组tuple 字典dictionary
- 【Python基础】之set, list, dictionary
- python Dictionary
- python Dictionary
- Python Dictionary
- Eclipse常用快捷键
- Solr安装及配置Solr的下载Solr的文件夹结构
- java--对象引用与对象的区别(转载)
- Spring 5.0.0参考文档中文完整版
- TODO的使用以及自定义
- Python学习之dictionary
- @那些想要转行AI的人:送你一份人工智能入门指南
- 数据结构中的栈
- 机器学习基本概念
- 机器学习算法-K近邻算法(1)
- 使用Service部署Spring Boot
- 决策树
- 用户不在sudoers文件中的解决方法
- 小白教学式,八皇后问题,Python生成器解法