Object II and Dictionary

Class objectives

Syntax table

Syntax
Description
Dictionary
It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

Dictionary

How to define a dictionary?

dic = {'color':'颜色', 'name':'名字,名称', 'father':'父亲,爸爸', 'computer':'电脑,计算机'}
print(dic)

How to add a value to Dictionary?

dic['program'] = '程序'

How to change the value of a key?

dic['name'] = '名称'

How to delete a key/value?

del dic['computer']

Looping techniques

dic = {'color':'颜色', 'name':'名字,名称', 'father':'父亲,爸爸', 'computer':'电脑,计算机'}
for key, value in dic.items():
	print(key, value)
dic = {'color':'颜色', 'name':'名字,名称', 'father':'父亲,爸爸', 'computer':'电脑,计算机'}
for each_word in dic:
	print(dic[each_word])

Students information system design

# Code is coming soon

Homework: Recall previous Python knowledge in a dictionary

Given a class with two functions __init__(), add and show.

  • __init__(): Initializes the class
  • add(): Adds a new key/value to the dictionary
  • show(): Shows all items in the dictionary
Basic skeleton of the code:
class Students:
	def __init__(self, dic):

	def add(self, key, value):

	def show(self):
Expected result for example:

Name: First class we have learnt: How to draw shapes in Turtle. How to use basic for loop.