Dictionaries
Python Basics Lesson 12 2:36 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Store a book in a list and you have to remember which position holds what.
把一本书的信息存进列表,你就得记住每个位置放的是什么。
Was slot one the number of pages, or the year?
下标 1 是页数,还是年份?
Six months later you will guess wrong.
半年之后你多半会猜错。
A dictionary fixes that by labelling every value, so you ask for it by name: book, square brackets, pages.
字典解决了这个问题:它给每个值贴上标签,你直接按名字去取: book 。
Nothing to remember, and the code says what it means.
什么都不用记,代码本身就说清楚了它的意思。
You write a dictionary in curly brackets.
字典写在花括号里面。
Inside, each entry is two things with a colon between them, and the entries are separated by commas.
里面每一项都是两个东西,中间用冒号隔开, 各项之间用逗号分开。
The key is the name you will look it up by — usually a string — and the value is whatever you are storing: a number, a string, even another list.
键是你以后用来查找的名字——通常是字符串—— 值则是你要存的东西:数字、字符串,甚至另一个列表。
Keys must be unique; write the same key twice and the second one simply wins.
键必须唯一;同一个键写两次,后写的那个直接生效。
Square brackets do three jobs.
方括号做三件事。
With a key inside, they read the value.
里面写上键,它就读出对应的值。
Assign to that same expression and it replaces the value — score becomes eighty-five.
对同一个表达式赋值,就会替换掉原来的值——score 变成 85。
And here is the one that surprises people: assign to a key that is not there yet, and the dictionary grows a new entry rather than complaining.
还有一个让人意外的:给一个还不存在的键赋值,字典不会报错, 而是新增一项。
Reading a missing key is different — that is a KeyError.
读一个不存在的键就不一样了——那会得到 KeyError。
This is the shape your exam calls a record: one dictionary holding the fields of one thing — one student's name and score, one book's title and pages.
这正是考试里叫做“记录”的结构:一个字典装着一个事物的各个字段—— 一个学生的姓名和分数,一本书的书名和页数。
And the moment you have three of them, you put them in a list of records, loop over it, and read the fields by name.
而当你有了三条这样的记录,你就把它们放进一个记录列表里,遍历它, 再按名字读取字段。
That pair — a list of dictionaries — is how nearly every real data set you will meet is shaped.
列表套字典这一对组合, 几乎就是你以后会遇到的每一份真实数据的样子。
Now the lesson's third task: add up the values in a dictionary of prices.
现在做课程里的第三道题:把一个价格字典里的值加起来。
The accumulator is the same as ever, but watch the loop — looping a dictionary gives you the keys, not the values.
累加器还是老样子,但要注意那个循环——遍历字典给你的是键,不是值。
So on each pass you take the key and look up its value with square brackets.
所以每一轮你拿到键,再用方括号查出它的值。
Apple gives three, pear gives two, plum gives five, and the total is ten.
apple 是 3,pear 是 2,plum 是 5,总和是 10。
Four things to take with you.
带走四点。
One: a dictionary looks values up by key, not by position — that is the whole difference from a list.
第一:字典按键查值,而不是按位置——这就是它和列表的全部区别。
Two: assigning to a key that does not exist adds it.
第二:给一个不存在的键赋值,就会新增这一项。
Three: looping a dictionary gives you its keys, so look the value up inside the loop.
第三:遍历字典给你的是键,所以要在循环里面把值查出来。
Four: one dictionary is one record, and a list of them is a table.
第四:一个字典就是一条记录,一列表这样的记录就是一张表。
Now do the three tasks.
现在去做那三道题。