Coursera课程《Python Data Structures》 密歇根大学 Charles Severance

Week5 Dictionary

9.1 Dictionaries

字典就像是一个包,而这个包里的每样东西都整整齐齐地贴好了标签,于是我们可以通过标签来找到我们想要的东西。而且注意,字典这个包是无序的,所以它不能根据顺序索引,只能根据标签。

>>> purse = dict()
>>> purse['money'] = 12
>>> purse['candy'] = 3
>>> purse['tissues'] = 75
>>> print(purse)
{'money':12, 'tissues':75, 'candy':3}
>>> print(purse['candy'])
3
>>> purse['candy'] = purse['candy'] + 2
>>> print(purse)
{'money':12, 'tissues':75, 'candy': 5}

9.2 Counting with Dictionaries

我们可以使用"in"来查看,是否某个key在这个字典里。

>>> ccc = dict()
>>> print(ccc['csev'])
Traceback (most recent call last):
File "<stdin", line 1, in <module>
KeyError: 'csev'
>>> 'csev' in ccc
False

字典的get()方法是查看是否一个key已经在字典里,如果没有在的话,那就新建一个key,把它附上默认值。

比如下面这两段代码,其实功能是一样的。

if name in counts:
x = counts[name]
else:
x = 0
 x = counts.get(name, 0)

所以使用get()来计数的话会更加方便。

counts = dict()
names = ['csev', 'cwen', 'csev', 'zqian', 'cwen']
for name in names:
counts[name] = counts.get(name, 0) + 1
print(counts)

输出结果就是

{'csev':2,'zqian':1,'cwen':2}

9.3 Dictionaries and Files

计数的一个基本模式是这样的。

counts = dict()
print('Enter a line of text:')
line = input('') words = line.split() print('Words:', words) print('Counting...')
for word in words:
counts[word] = counts.get(word, 0) + 1
print('Counts', counts)

我们可以使用keys(), values(), items()这些方法来分别获得字典的key,值或者全部

>>> jjj = {'chuck':1, 'fred':42, 'jan':100}
>>> print(list(jjj))
['jan', 'chuck', 'fred']
>>> print(jjj.keys())
['jan', 'chuck', 'fred']
>>> print(jjj.values())
[100, 1, 42]
>>> print(jjj.items())
[('jan', 100), ('chuck', 1), ('fred', 42)]

我们还可以使用两个循环变量同时对key和value进行循环。

jjj = {'chuck':1, 'fred':42, 'jan': 100}
for aaa,bbb in jjj.item():
print(aaa,bbb)

那么接下来我们就可以读取文件,来对里面的文本进行计数了。

name = input('Enter file:')
handle = open(name) counts = dict()
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1 bigcount = None
bigword = None
for word, count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count print(bigword, bigcount)

9.4 Assignment

作业的代码如下

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name) counts = dict()
for line in handle:
words = line.split()
if len(words) < 1 or words[0] != 'From':
continue
counts[words[1]] = counts.get(words[1], 0) + 1 bigcount = None
bigword = None
for word, count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count print(bigword, bigcount)

《Python Data Structures》Week5 Dictionary 课堂笔记的更多相关文章

  1. 【Python学习笔记】Coursera课程《Python Data Structures》 密歇根大学 Charles Severance——Week6 Tuple课堂笔记

    Coursera课程<Python Data Structures> 密歇根大学 Charles Severance Week6 Tuple 10 Tuples 10.1 Tuples A ...

  2. 《Python Data Structures》 Week4 List 课堂笔记

    Coursera课程<Python Data Structures> 密歇根大学 Charles Severance Week4 List 8.2 Manipulating Lists 8 ...

  3. 潭州课堂25班:Ph201805201 爬虫基础 第七课 Python与常见加密方式 (课堂笔记)

    打开图形界面  18版 Python与常见加密方式 前言 我们所说的加密方式,都是对二进制编码的格式进行加密的,对应到Python中,则是我们的Bytes. 所以当我们在Python中进行加密操作的时 ...

  4. 学习笔记之Problem Solving with Algorithms and Data Structures using Python

    Problem Solving with Algorithms and Data Structures using Python — Problem Solving with Algorithms a ...

  5. [译]The Python Tutorial#5. Data Structures

    [译]The Python Tutorial#Data Structures 5.1 Data Structures 本章节详细介绍之前介绍过的一些内容,并且也会介绍一些新的内容. 5.1 More ...

  6. 剪短的python数据结构和算法的书《Data Structures and Algorithms Using Python》

    按书上练习完,就可以知道日常的用处啦 #!/usr/bin/env python # -*- coding: utf-8 -*- # learn <<Problem Solving wit ...

  7. Python Tutorial 学习(五)--Data Structures

    5. Data Structures 这一章来说说Python的数据结构 5.1. More on Lists 之前的文字里面简单的介绍了一些基本的东西,其中就涉及到了list的一点点的使用.当然,它 ...

  8. 《Data Structures and Algorithm Analysis in C》学习与刷题笔记

    <Data Structures and Algorithm Analysis in C>学习与刷题笔记 为什么要学习DSAAC? 某个月黑风高的夜晚,下班的我走在黯淡无光.冷清无人的冲之 ...

  9. ocp11g培训内部教材_052课堂笔记(042)_体系架构

    OCP 052 课堂笔记 目录 第一部分: Oracle体系架构... 4 第一章:实例与数据库... 4 1.Oracle 网络架构及应用环境... 4 2.Oracle 体系结构... 4 3. ...

随机推荐

  1. 什么情况下会出现undefined

    1.函数定义形参不传值,2.预解释,只声明不定义时输出变量3.对象取属性值,属性值不存在

  2. linux Apache 的安装

    rpm –qa httpd 查询是否安装了 Apache rpm –e 包名卸载安装程序 rpm –e --nodeps 包名卸载安装程序不产生依赖 #检查是否安装有依赖库 yum install – ...

  3. mknod - 建立块专用或字符专用文件

    总览 mknod [options] name {bc} major minor mknod [options] name p GNU 选项(缩写): [-m mode] [--help] [--ve ...

  4. H5微信授权登录

    这里介绍H5微信授权登录,采用了微信公众号授权原理,是oauth2的登录授权方式,简单的来讲,就是用户通过手机微信确认登录之后,微信方会返回一个授权码code给回第三方(接入方),这个授权码code一 ...

  5. AtCoder Beginner Contest 088 C Takahashi's Information

    Problem Statement We have a 3×3 grid. A number ci,j is written in the square (i,j), where (i,j) deno ...

  6. activity manager

    首先 activity manager 作为一个独立的服务存在,所有系统中的所有 app 的 activity 都通过这个 service 来管理 同时 activity manager 维护着多个 ...

  7. pymongo操作mongo数据库的查操作

    一:  数据结构 { "_id" : ObjectId("5de8a5b748a75a8d48b72bdc"), ", ", ", ...

  8. CentOS8 安装部署Apache+Php+MariaDB(pdo扩展)

    使用新的CentOS8系统架设PHP服务器,因现在主流数据库mysql已闭源了,所以现在改为使用MariaDB.而php7以后不支持mysqli链接,只有pdo方式,为了安装pdo扩展,所以重新编译安 ...

  9. 【leetcode】1129. Shortest Path with Alternating Colors

    题目如下: Consider a directed graph, with nodes labelled 0, 1, ..., n-1.  In this graph, each edge is ei ...

  10. 【bzoj2946】[Poi2000]公共串

    *题目描述: 给出几个由小写字母构成的单词,求它们最长的公共子串的长度. 任务: l 读入单词 l 计算最长公共子串的长度 l 输出结果 *输入: 文件的第一行是整数 n,1<=n<=5, ...